[英]How can I add input values to a result list below and allow the same text input field to continue to add more?
I have a single text field and an accompanying "add" button: 我有一个文本字段和一个附带的“添加”按钮:
<fieldset id="itemList">
<input type="text" id="addItem" name="addItem">
<input type="button" name="add" value="add">
</fieldset>
Whenever someone clicks "add" I'd like to add the new item to the list below and clear the input field above. 每当有人点击“添加”时,我想将新项目添加到下面的列表中并清除上面的输入字段。
<hr>
<ol id="resultList">
<li>just example</li>
<li>new text input</li>
<li>last entered item</li>
</ol>
I'm not sure how to accomplish this in jQuery. 我不知道如何在jQuery中实现这一点。 Can you help? 你能帮我吗?
For bonus, I'd like to limit the list to 10. So I need to somehow count the number of list items and make the above form's display contingent on <11 list items. 对于奖金,我想将列表限制为10.因此,我需要以某种方式计算列表项的数量,并使上述表单的显示取决于<11个列表项。
Can you help? 你能帮我吗?
function addItem(){
var list = $("#resultList");
var count = list.find("li").size();
if(count < 10){
var input = $("input[name=addItem]");
var item = input.val();
list.append(("<li>"+item+"</li>"));
input.val(" "); // clear field
}else{
// already have 10 items
}
}
$("input[name=add]").click(addItem);
jQuery(function($){
$('input[name="add"]').click(function() {
if($('#resultList li').length < 10)
{ value = $('input[name="addItem"]').val();
$('ol li:last').after("<li>" + value + "</li>");
$('input[name="addItem"]').val(""); }
if($('#resultList li').length == 10)
{ $('input[name="addItem"]').css("display", "none");
$('input[name="add"]').css("display", "none"); }
});
});
Working jsFiddle here: http://jsfiddle.net/bhZdz/2/ 在这里工作jsFiddle: http : //jsfiddle.net/bhZdz/2/
Edited because I didn't see the last part of your question, form hides after 10th element is added now. 编辑,因为我没有看到你的问题的最后一部分,现在添加第10个元素后隐藏形式。
Try this 尝试这个
$('input[type=button]').click(function(){
$('#resultList').append('<li>'+$('#addItem').val()+'</li>');
$('#addItem').val("");
}
);
You can also use input[name=add]
你也可以使用input[name=add]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.