$('input[name="accounts"]').on('click', function() {
$('input[name="accounts"]:checked').each(function() {
if (index == 0) {
txt = $(this).val();
$("#accounts-text").html(txt);
} else {
$("#accounts-text").append(txt);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><b>Accounts</b></label><br>
<input type="checkBox" name="accounts" value="Gmail"> Gmail
<br>
<input type="checkBox" name="accounts" value="Facebook"> Facebook
<br>
<input type="checkBox" name="accounts" value="Instagram"> Instagram
<br>
<div class="form-group">
<label>Accounts: </label>
<h5 id="accounts-text"></h5>
</div>
在上面的代码中,帮助我在尝试在同一页面中选择显示复选框值时找出错误.
解决方法:
您可以使用map()和get()来获取所有值.这将返回所有已检查值的数组.使用join()将数组转换为字符串.
$('input[name="accounts"]').on('click', function() {
var result = $('input[name="accounts"]:checked').map(function() {
return this.value;
}).get();
$("#accounts-text").html(result.join("<br />"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><b>Accounts</b></label><br>
<input type="checkBox" name="accounts" value="Gmail"> Gmail
<br>
<input type="checkBox" name="accounts" value="Facebook"> Facebook
<br>
<input type="checkBox" name="accounts" value="Instagram"> Instagram
<br>
<div class="form-group">
<label>Accounts: </label>
<h5 id="accounts-text"></h5>
</div>