jQuery 在单击时显示选择内的输入数据
我有一个带有按钮的文本输入。当我填写输入并单击按钮时,我想将该信息添加到选择中。请任何人帮忙,我在任何地方都找不到例子。
Input & button
<input id="new_menu_name" type="text" name="new_menu_name" placeholder="Please enter your menu title">
<input class="add_menu_item" name="add_menu_item" value="Add" type="button">
Select
<select name="menu_items" id="menu_items" size="8" multiple="multiple" style="height:200px; width:250px;">
</select>
我尝试过使用这个脚本,但没有运气
$(document).ready(function() {
$(".add_menu_item").click(function(){
$('#menu_items').
append($("<option></option>").
attr("value").
text(value));
});
I have a text input with a button. When I fill in the input and click the button I want to add that information to a select. Please can anyone one help, I can't find an example anywhere.
Input & button
<input id="new_menu_name" type="text" name="new_menu_name" placeholder="Please enter your menu title">
<input class="add_menu_item" name="add_menu_item" value="Add" type="button">
Select
<select name="menu_items" id="menu_items" size="8" multiple="multiple" style="height:200px; width:250px;">
</select>
I have tried using this script but with no luck
$(document).ready(function() {
$(".add_menu_item").click(function(){
$('#menu_items').
append($("<option></option>").
attr("value").
text(value));
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
attr
时,您实际上并未设置值:您正在检索value
属性的当前值。您应该使用val
函数来设置值:现在我已经看过您的完整代码,很明显另一个问题是您没有设置
value
变量。我想你可能想要类似 this 的东西:(还要注意的是,我已经更改了小提琴以使用 jQuery而不是 Mootools。)
When you call
attr
, you're not actually setting a value: you're retrieving the current value of thevalue
attribute. You should use theval
function to set the value:Now that I've seen your full code, it's clear that the other problem is that you aren't setting the
value
variable. I think you probably want something like this:(NB also that I've changed the fiddle to use jQuery rather than Mootools.)
尝试将
attr("value").text(value)
更改为attr("value",value)
try changing
attr("value").text(value)
toattr("value",value)
将其更改为
attr("value", value)
。attr("value")
返回属性的值。change that to
attr("value", value)
. Theattr("value")
returns the value of the attribute.