简体   繁体   English

获取选中复选框的值?

[英]Get the value of checked checkbox?

So I've got code that looks like this:所以我有这样的代码:

<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">

I just need Javascript to get the value of whatever checkbox is currently checked.我只需要 Javascript 来获取当前选中的任何复选框的值。

EDIT : To add, there will only be ONE checked box.编辑:要添加,将只有一个复选框。

None of the above worked for me but simply use this:以上都不适合我,只是简单地使用这个:

document.querySelector('.messageCheckbox').checked;

Happy coding.快乐编码。

For modern browsers :对于现代浏览器

var checkedValue = document.querySelector('.messageCheckbox:checked').value;

By using jQuery :通过使用jQuery

var checkedValue = $('.messageCheckbox:checked').val();

Pure javascript without jQuery :没有jQuery纯 javascript

var checkedValue = null; 
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           checkedValue = inputElements[i].value;
           break;
      }
}

I am using this in my code.Try this我在我的代码中使用这个。试试这个

var x=$("#checkbox").is(":checked");

If the checkbox is checked x will be true otherwise it will be false.如果复选框被选中, x将为真,否则为假。

in plain javascript:在普通的javascript中:

function test() {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
    }
}
function selectOnlyOne(current_clicked) {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        cboxes[i].checked = (cboxes[i] == current);
    }
}

This does not directly answer the question, but may help future visitors.这并不能直接回答问题,但可能对未来的访问者有所帮助。


If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.如果你想让一个变量始终是复选框的当前状态(而不是一直检查它的状态),你可以修改onchange事件来设置该变量。

This can be done in the HTML:这可以在 HTML 中完成:

<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>

or with JavaScript:或使用 JavaScript:

cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})

 $(document).ready(function() { var ckbox = $("input[name='ips']"); var chkId = ''; $('input').on('click', function() { if (ckbox.is(':checked')) { $("input[name='ips']:checked").each ( function() { chkId = $(this).val() + ","; chkId = chkId.slice(0, -1); }); alert ( $(this).val() ); // return all values of checkboxes checked alert(chkId); // return value of checkbox checked } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="checkbox" name="ips" value="12520"> <input type="checkbox" name="ips" value="12521"> <input type="checkbox" name="ips" value="12522">

Use this:用这个:

alert($(".messageCheckbox").is(":checked").val())

This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.这假设要检查的复选框具有“messageCheckbox”类,否则您必须检查输入是否为复选框类型等。

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
    alert(value);
}

None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):当未选中该框时,上述任何一项都不对我有用,而不会在控制台中引发错误,因此我按照这些方式做了一些事情(onclick 和复选框功能仅用于演示目的,在我的用例中,它是更大的表单提交功能):

 function checkbox() { var checked = false; if (document.querySelector('#opt1:checked')) { checked = true; } document.getElementById('msg').innerText = checked; }
 <input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>

If you're using Semantic UI React , data is passed as the second parameter to the onChange event.如果您使用Semantic UI Reactdata将作为第二个参数传递给onChange事件。

You can therefore access the checked property as follows:因此,您可以按如下方式访问已checked属性:

<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />

If you want to get the values of all checkboxes using jQuery, this might help you.如果您想使用 jQuery 获取所有复选框的值,这可能对您有所帮助。 This will parse the list and depending on the desired result, you can execute other code.这将解析列表,并根据所需的结果,您可以执行其他代码。 BTW, for this purpose, one does not need to name the input with brackets [].顺便说一句,为此,不需要用括号 [] 命名输入。 I left them off.我离开了他们。

  $(document).on("change", ".messageCheckbox", function(evnt){
    var data = $(".messageCheckbox");
    data.each(function(){
      console.log(this.defaultValue, this.checked);
      // Do something... 
    });
  }); /* END LISTENER messageCheckbox */

pure javascript and modern browsers纯 javascript 和现代浏览器

// for boolean
document.querySelector(`#isDebugMode`).checked

// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize

Example例子

 <form> <input type="checkbox" id="isDebugMode"><br> <input type="checkbox" value="3" id="size"><br> <input type="submit"> </form> <script> document.querySelector(`form`).onsubmit = () => { const isDebugMode = document.querySelector(`#isDebugMode`).checked const defaultSize = "10" const size = document.querySelector(`#size:checked`)?.value ?? defaultSize // 👇 for defaultSize is undefined or null // const size = document.querySelector(`#size:checked`)?.value console.log({isDebugMode, size}) return false } </script>

Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element).惊讶地发现这里没有有效的 vanilla JavaScript 解决方案(当您遵循最佳实践并对每个 HTML 元素使用不同的 ID 时,投票最高的答案不起作用)。 However, this did the job for me:但是,这对我有用:

Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) { 
      return v.value; 
  });

You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.您可以通过jQueryJavaScript使用以下方法来检查checkbox是否被单击。

$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript

To obtain the value checked in jQuery:要获取在 jQuery 中检查的值:

$(".messageCheckbox").is(":checked").val();

In my project, I usually use this snippets:在我的项目中,我通常使用这个片段:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.它运作良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM