[英]jQuery: Get checked checkbox value in a div
I got a survey, each possible reply is a checkbox and each question is divided in a div that has an id number. 我进行了调查,每个可能的答复都是一个复选框,每个问题被划分为一个具有ID编号的div。 I must to create a function that return which checkbox is selected and return as an int.
我必须创建一个函数,该函数返回选中了哪个复选框并以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>
Here is the function i've wrote, but at the time I got "undefined" (I call this function when jquery.steps.js
change step.) 这是我编写的函数,但是在我得到“未定义”的时候(当
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()
}
});
}
This value will be putted in a json call and send to the server. 此值将放入json调用中并发送到服务器。
I think I'm using the wrong selector cause I get undefined when I select the checkboxes. 我认为我使用了错误的选择器,原因是当我选择复选框时,我无法定义。
$(selector).each(function() {
is a new function in itself - when it runs, if you return
inside of it, you're returning the value to the jQuery iteration function (which completely ignores the return value), not to your outer getStepCheckboxes
. $(selector).each(function() {
这本身就是一个新的功能-在运行时,如果你return
的这里面,你返回值jQuery的迭代函数(这完全忽略了返回值),而不是到您的外部getStepCheckboxes
。
But you don't need jQuery for this - you can just use vanilla JS. 但您不需要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);
}
You can use the some function of array on a jquery element to break the loop when it is found. 您可以在jquery元素上使用array的some函数来打破循环。 You can also use the filter jquery function https://api.jquery.com/filter/ but it won't stop at the first occurence.
您还可以使用过滤器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;
}
OR 要么
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.