[英]jQuery: Get checked checkbox value in a div
我进行了调查,每个可能的答复都是一个复选框,每个问题被划分为一个具有ID编号的div。 我必须创建一个函数,该函数返回选中了哪个复选框并以int形式返回。
<div class="row" id="replies-{{ question.id }}">
{% for reply in func.replies(question.id) %}
<div class="col-md-12">
<div class="btn-group-toggle" data-toggle="buttons" >
<label class="btn btn-block btn-secondary">
<input type="checkbox" autocomplete="off" value="{{ reply.id }}" data-id="{{ reply.id }}" data-question="{{ question.id }}" data-test="{{ question.test }}"> {{ reply.reply }}
</label>
</div>
</div>
{% endfor %}
</div>
这是我编写的函数,但是在我得到“未定义”的时候(当jquery.steps.js
更改step时,我称此函数。)
function getStepChekboxes(id) {
var selector = '#replies-' + id + ':checkbox:checked';
console.log(selector);
$(selector).each(function() {
if ($(this).data("question") == id) {
return $(selector).val()
}
});
}
此值将放入json调用中并发送到服务器。
我认为我使用了错误的选择器,原因是当我选择复选框时,我无法定义。
$(selector).each(function() {
这本身就是一个新的功能-在运行时,如果你return
的这里面,你返回值jQuery的迭代函数(这完全忽略了返回值),而不是到您的外部getStepCheckboxes
。
但您不需要jQuery,就可以使用Vanilla JS。
function getStepChekboxes(id) {
const selector = '#replies-' + id + ':checkbox:checked';
const foundElement = [...document.querySelectorAll(selector)]
.find(element => element.dataset.question === id);
if (foundElement) return parseInt(foundElement.value, 10);
}
您可以在jquery元素上使用array的some函数来打破循环。 您还可以使用过滤器jquery函数https://api.jquery.com/filter/,但它不会在第一次出现时停止。
function getStepChekboxes(id) {
var selector = '#replies-' + id + ':checkbox:checked';
console.log(selector);
var result;
Array.prototype.some.call($(selector),function(el) {
if ($(el).data("question") == id) {
result = el.value
return true
}
});
return result;
}
要么
function getStepChekboxes(id) {
var selector = '#replies-' + id + ':checkbox:checked';
console.log(selector);
return $(selector).filter(function(i,el) {
return $(el).data("question") == id
}).val();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.