jQuery 更改输入文本值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5709258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery change input text value
提问by Joricam
I can't find the right selector for:
我找不到正确的选择器:
<input maxlength="6" size="6" id="colorpickerField1" name="sitebg" value="#EEEEEE" type="text">
I want to change the value to = 000000. I need the selector to find the "name" not the id of the text input.
我想将值更改为 = 000000。我需要选择器来查找“名称”而不是文本输入的 id。
Shouldn't this work?:
这不应该工作吗?:
$("text.sitebg").val("000000");
The presented solution does not work, what's the problem with this?
提出的解决方案不起作用,这是什么问题?
$.getJSON("http://www.mysitehere.org/wp-content/themes/ctr-theme/update_genform.php",function(data) {
$("#form1").append(data.sitebg);
$('input.sitebg').val('000000');
});
The JSON data is working correctly; the idea is to later pass the JSON values into the form input text values. But is not working :(
JSON 数据工作正常;这个想法是稍后将 JSON 值传递到表单输入文本值中。但不起作用:(
回答by Jason
no, you need to do something like:
不,您需要执行以下操作:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
但如果可以的话,你真的应该使用唯一的 ID。
You can also get more specific, such as:
您还可以获得更具体的信息,例如:
$('input[type=text].sitebg').val('000000');
EDIT:
编辑:
do this to find your input based on the name attribute:
这样做以根据 name 属性查找您的输入:
$('input[name=sitebg]').val('000000');
回答by Vladimir Kroz
jQuery way to change value on text input field is:
jQuery 更改文本输入字段值的方法是:
$('#colorpickerField1').attr('value', '#000000')
this will change attribute value
for the DOM element with ID #colorpickerField1
from #EEEEEE
to #000000
这将改变属性value
用于与ID的DOM元素 #colorpickerField1
从#EEEEEE
至#000000
回答by MGE
Best practice is using the identify directly:
最佳实践是直接使用标识:
$('#id').val('xxx');
$('#id').val('xxx');
回答by Richelly Italo
When set the new value of element, you need call trigger change.
设置元素的新值时,需要调用触发器更改。
$('element').val(newValue).trigger('change');
$('element').val(newValue).trigger('change');
回答by Robert Ingrum
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
只是添加到 Jason 的答案中,.
选择器仅适用于类。如果要选择元素、id 或类以外的内容,则需要将其括在方括号中。
e.g.
例如
$('element[attr=val]')
$('element[attr=val]')