Javascript 获取选中复选框的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11599666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:29:26  来源:igfitidea点击:

Get the value of checked checkbox?

javascriptcheckbox

提问by Matthew 'mandatory' Bryant

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.

编辑:要添加,只会有一个复选框。

回答by JanBorup

None of the above worked for me but simply use this:

以上都不适合我,只是简单地使用这个:

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

Happy coding.

快乐编码。

回答by Engineer

For modern browsers:

对于现代浏览器

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

By using jQuery:

通过使用jQuery

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

Pure javascript without jQuery:

纯 javascript 没有jQuery

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

回答by user1683014

I am using this in my code.Try this

我在我的代码中使用这个。试试这个

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

If the checkbox is checked xwill be true otherwise it will be false.

如果复选框被选中,则为x真,否则为假。

回答by Stano

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);
    }
}

回答by Marinha do Nascimento

$(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">

回答by Joe Iddon

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 onchangeevent 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})

回答by HymanJoe

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”类,否则您必须检查输入是否为复选框类型等。

回答by Alien

<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);
}

回答by spice

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>

回答by Dave Clark

If you're using Semantic UI React, datais passed as the second parameter to the onChangeevent.

如果您使用Semantic UI Reactdata则作为第二个参数传递给onChange事件。

You can therefore access the checkedproperty as follows:

因此,您可以checked按如下方式访问该属性:

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