使用 JQuery 设置文本框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17558053/
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
Set value of textbox using JQuery
提问by Narabhut
My Jade template -
我的翡翠模板 -
input#main_search.span2(
style = 'height: 26px; width: 800px;' ,
type = 'text',
readonly='true',
name='searchBar',
value='test'
)
JS file -
JS文件——
$('#searchBar').val('hi')
console.log('sup')
Console output -
控制台输出 -
sup
But searchBar
value stats at test. What am I doing wrong?
但searchBar
在测试中的价值统计。我究竟做错了什么?
回答by Sushanth --
You are logging sup
directly which is a string
您正在sup
直接记录这是一个字符串
console.log('sup')
Also you are using the wrong id
您也使用了错误的 ID
The template says #main_search
but you are using #searchBar
模板说,#main_search
但你正在使用#searchBar
I suppose you are trying this out
我想你正在尝试这个
$(function() {
var sup = $('#main_search').val('hi')
console.log(sup); // sup is a variable here
});
回答by Zevi Sternlicht
Make sure you have the right selector, and then wait until the page is ready and that the element exists until you run the function.
确保您有正确的选择器,然后等到页面准备好并且元素存在,直到您运行该函数。
$(function(){
$('#searchBar').val('hi')
});
As Derek points out, the ID is wrong as well.
正如 Derek 指出的那样,ID 也是错误的。
Change to $('#main_search')
改成 $('#main_search')
回答by AZee
1) you are calling it wrong way try:
1)你用错误的方式调用它尝试:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
2) 如果它不起作用,请在页面末尾调用您的 .js 文件或在 document.ready 事件上触发您的函数
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
回答by Derek Peterson
You're targeting the wrong item with that jQuery selector. The name
of your search bar is searchBar
, not the id
. What you want to use is $('#main_search').val('hi')
.
您使用该 jQuery 选择器定位了错误的项目。在name
搜索栏的是searchBar
,不是id
。您要使用的是$('#main_search').val('hi')
.
回答by SagarPPanchal
$(document).ready(function() {
$('#main_search').val('hi');
});