javascript Jquery 单击以更改表单字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8597730/
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 Click to Change Form Field Value
提问by Andrei
I have this code:
我有这个代码:
<input type="text" name="frameSelection" id="frameSelection" value="Option 1" />
<a id="change">Change to Option 2</a>
When I click on the link I want to change the field value into "Option 2". How can I do that?
当我点击链接时,我想将字段值更改为“选项 2”。我怎样才能做到这一点?
回答by James Allardice
Very simple. Use click
to attach an event handler to the click
event, and val
to set the value:
很简单的。使用click
将事件处理程序附加到click
事件,并val
设定值:
$("#change").click(function() {
$("#frameSelection").val("Option 2");
});
As mentioned in other answers, you may want to prevent the default behaviour of the link, but with your code as it currently is in the question (with no href
attribute on the a
element) that's not necessary. Just bear it in mind if that could change.
正如其他答案中提到的,您可能希望阻止链接的默认行为,但是使用您当前在问题中的代码(元素href
上没有属性a
),这是不必要的。如果可以改变,请记住它。
回答by David says reinstate Monica
With jQuery:
使用 jQuery:
$('#change').click(
function(e){
e.preventDefault; // if your a has an href attribute, this prevents the browser
// following that link.
$('#frameSelection').val("Option 2");
});
References:
参考: