[英]How to dynamically add List items in jQuery
I am developing an mobile app in which i want to populate ListView once the user fill up the form and click on submit button. 我正在开发一个移动应用程序,一旦用户填写表单并单击“提交”按钮,我想在其中填充ListView。
I know how to give List View in jQuery but how to populate items in it dynamically at run time? 我知道如何在jQuery中提供列表视图,但如何在运行时动态填充其中的项目?
Are you looking for something like this? 您是否正在寻找这样的东西?
HTML: HTML:
<div id="listView"></div>
<input type="button" id="mybutt" value="Submit" />
javascript/jQuery: javascript / jQuery:
$('#mybutt').click(function() {
var out = '<ul><li>Item One</li><li>Item Two</li><li>Item Three</li></ul>';
$('#listView').html(out);
});
Responding to your comment: "what i need is on click of button form gets submitted and firstname which user enters on form will get added in list" 回应您的评论: “我需要的是单击按钮表单,然后提交,用户在表单上输入的名字将添加到列表中”
First, you need to remain on the page after the form was submitted. 首先,提交表单后,您需要保留在页面上。 To do that, you should add
e.preventDefault();
为此,您应该添加
e.preventDefault();
in your submit routine: 在您的提交例程中:
$( "#target" ).submit(function( event ) {
//Manually collect form values and
//Use ajax to submit form values here (see notes at bottom)
event.preventDefault();
});
Next, you want to get the data that was in the desired field, and add that to the <ul>
. 接下来,您想要获取所需字段中的数据,并将其添加到
<ul>
。 Therefore, change the above like this: 因此,像这样更改上面的内容:
$( "#target" ).submit(function( event ) {
var fn = $('#fname').val();
$('ul').append('<li>' +fn+ '</li>');
//Manually collect form values and
//Use ajax to submit form values here (see notes at bottom)
event.preventDefault();
});
For the AJAX bit, see this post for tips. 对于AJAX位, 请参阅这篇文章以获取提示。
Note that you can use $('#formID').serialize();
请注意,您可以使用
$('#formID').serialize();
to quickly serialize all form data. 快速序列化所有表单数据。
js fiddle: js小提琴:
http://jsfiddle.net/7PzcN/1/ http://jsfiddle.net/7PzcN/1/
html: 的HTML:
<div id="listView"></div>
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="button" id="mybutt" value="Submit" />
jquery: jQuery的:
$('#mybutt').click(function() {
var out = '<ul>';
$("input[type=text]").each(function() {
out += "<li>" + $(this).val() + "</li>";
});
out += "</ul>";
$('#listView').html(out);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.