我正在构建一个简单的购物车,访问者可以选择他们想要的一些项目,点击"下一步"按钮,并查看他们刚刚选择的事物的确认列表。我希望每个项目的每个项目都显示确认列表。
HTML选择
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
HTML确认列表
<div id='confirmation_list' style='display:none;'>
<h2>You have selected item 1</h2>
<h2>Your have selected item 2 </h2>
</div>
JS
$(function(){
$('#confirm').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
我最终想要替换“你已经选择了第2项”的字样。在h2s中,从每个复选框中选择值。使用上面的代码,我能够将每个复选框的值收集到数组val中,但是难以循环并显示它们。
任何建议都将受到赞赏。
答案 0 :(得分:2)
尝试
$(function () {
$('#confirm').click(function () {
var val = [];
var els = $('input:checkbox:checked').map(function (i) {
return $('<h2 />', {
text: 'You have selected item \'' + this.value + '\''
})
}).get();
$('#confirmation_list').empty().append(els).show()
});
});
演示:Fiddle
答案 1 :(得分:1)
试试这个
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
<div id='confirmation_list' style='display:none;'>
</div>
你的JS代码应该是
$(function () {
$('#confirm').click(function () {
$("#confirmation_list").empty();
$('input:checkbox:checked').each(function (i) {
$("#confirmation_list").append("<h2>You have selected item '" + $(this).val() + "'</h2>");
});
$("#confirmation_list").show();
});
});