我尝试在checkbox
字段中添加closest
的值。但我想我错过了什么。请参阅下面的代码:
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + ",";
});
$(this).closest('.divs').find(".result").val(output.trim());
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divs">
<input type="text" class="result"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<br><br>
<div class="divs">
<input type="text" class="result"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
&#13;
更新
我还想检查文本框是否为空,然后该值将返回empty
。我试过了
if($(this).closest('.divs').find('.result').val() == ""){
$(this).closest('.divs').find('.result').val("empty");
}
答案 0 :(得分:3)
第一个问题是你有多个具有相同Id,Use类的元素。
其次,您使用$("input:checked").each
获取所有选中的输入,但使用("input:checked").each
获取当前div.divs
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
var length = $(this).parent('.divs').find("input:checked").length;
$(this).parent('.divs').find("input:checked").each(function(index) {
output += $(this).val() + (index !== (length - 1) ? "," : "");
});
$(this).parent('.divs').find(".field_results").val(output.trim());
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divs">
<input type="text" class="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<br><br>
<div class="divs">
<input type="text" class="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
&#13;
答案 1 :(得分:3)
使用input type text
而不是classname
更改id
attr。通过父div
更新1
使用,
unsing map()
函数
Upadted 2
添加空值
$(document).ready(function(){
$("input:checkbox").change(function() {
var output =$(this).closest('.divs').find("input:checked").map(function() {
return $(this).val();
}).get();
var res = output.length ==0 ? 'empty' : output.join(',');
$(this).closest('.divs').find(".field_results").val(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divs">
<input type="text" class="field_results" placeholder="empty"><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<br><br>
<div class="divs">
<input type="text" class="field_results" placeholder="empty"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>