如何使用jQuery设置输入文本的值 [英] How to set value of input text using jQuery

查看:16
本文介绍了如何使用jQuery设置输入文本的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文本是这样的:

@Html.LabelFor(model => model.EmployeeId, "员工编号")

<div class="editor-field textBoxEmployeeNumber">@Html.EditorFor(model => model.EmployeeId)@Html.ValidationMessageFor(model => model.EmployeeId)

产生以下 html

<label for="EmployeeId">员工编号</label>

<div class="editor-field textBoxEmployeeNumber"><input class="text-box single-line" data-val="true" data-val-number="EmployeeId 字段必须是数字."data-val-required="EmployeeId 字段是必需的."id="EmployeeId" name="EmployeeId" type="text" value=""/><span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>

我想使用 jquery 设置此输入文​​本的值,所以我这样做了:

但是,它不起作用......我的语法有什么错误?

解决方案

您的选择器正在检索文本框周围的 <div class='textBoxEmployeeNumber'> 而不是其中的输入.

//使用这个选择器访问 div 内的输入:$(函数(){$('.textBoxEmployeeNumber 输入').val("fgg");});

看到输出 HTML 后更新

如果 ASP.NET 代码可靠地输出带有 id 属性 id='EmployeeId' 的 HTML ,您可以更简单地使用:>

$(function () {$('#EmployeeId').val("fgg");});

如果失败,您将需要在浏览器的错误控制台中验证您没有其他导致此失败的脚本错误.上面的第一个示例在本演示中正常工作.

I have an input text which is this:

<div class="editor-label">
    @Html.LabelFor(model => model.EmployeeId, "Employee Number")
</div>

<div class="editor-field textBoxEmployeeNumber">
    @Html.EditorFor(model => model.EmployeeId) 
    @Html.ValidationMessageFor(model => model.EmployeeId)
</div>

Which produce following html

<div class="editor-label">
  <label for="EmployeeId">Employee Number</label>
</div>

<div class="editor-field textBoxEmployeeNumber">
  <input class="text-box single-line" data-val="true" data-val-number="The field EmployeeId must be a number." data-val-required="The EmployeeId field is required." id="EmployeeId" name="EmployeeId" type="text" value="" />

  <span class="field-validation-valid" data-valmsg-for="EmployeeId" data-valmsg-replace="true"></span>
</div>

I want to set the value of this input text using jquery so i did this:

<script type="text/javascript" language="javascript">
    $(function() {
        $('.textBoxEmployeeNumber').val("fgg");
    });
</script> 

however, it is not working... what is the error in my syntax?

解决方案

Your selector is retrieving the text box's surrounding <div class='textBoxEmployeeNumber'> instead of the input inside it.

// Access the input inside the div with this selector:
$(function () {
  $('.textBoxEmployeeNumber input').val("fgg");
});

Update after seeing output HTML

If the ASP.NET code reliably outputs the HTML <input> with an id attribute id='EmployeeId', you can more simply just use:

$(function () {
  $('#EmployeeId').val("fgg");
});

Failing this, you will need to verify in your browser's error console that you don't have other script errors causing this to fail. The first example above works correctly in this demonstration.

这篇关于如何使用jQuery设置输入文本的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆