jQuery 获取复选框值(如果选中)并在未选中时删除值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17717608/
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-26 19:49:05  来源:igfitidea点击:

jQuery get checkbox value if checked and remove value when unchecked

javascriptjqueryfunctioncheckbox

提问by JS-Hero

jQuery function to get checkbox value if checked and remove value if unchecked.

jQuery 函数在选中时获取复选框值,如果未选中则删除值。

example here

例子在这里

<input type="checkbox" id="check" value="3" />hiiii

<div id="show"></div>

function displayVals(){
var check = $('#check:checked').val();
    $("#show").html(check);
}
var qqqq = window.setInterval( function(){
        displayVals()
    },
    10
);

回答by adeneo

You don't need an interval, everytime someone changes the checkbox the changeevent is fired, and inside the event handler you can change the HTML of #showbased on wether or not the checkbox was checked :

您不需要间隔,每次有人更改复选框时change都会触发事件,并且在事件处理程序中,您可以#show根据复选框是否被选中来更改 HTML :

$('#check').on('change', function() {
    var val = this.checked ? this.value : '';
    $('#show').html(val);
});

FIDDLE

小提琴

回答by Tushar Gupta - curioustushar

Working Demo http://jsfiddle.net/cse_tushar/HvKmE/5/

工作演示http://jsfiddle.net/cse_tushar/HvKmE/5/

js

js

$(document).ready(function(){
    $('#check').change(function(){
        if($(this).prop('checked') === true){
           $('#show').text($(this).attr('value'));
        }else{
             $('#show').text('');
        }
    });
});

回答by Mahdy Aslamy

There is another way too:

还有一种方法:

  1. Using the new property method will return true or false.

    $('#checkboxid').prop('checked');

  2. Using javascript without libs

    document.getElementById('checkboxid').checked

  3. Using the JQuery's is()

    $("#checkboxid").is(':checked')

  4. Using attr to get checked

    $("#checkboxid").attr("checked")

  1. 使用新的属性方法将返回 true 或 false。

    $('#checkboxid').prop('checked');

  2. 在没有库的情况下使用 javascript

    document.getElementById('checkboxid').checked

  3. 使用 JQuery 的 is()

    $("#checkboxid").is(':checked')

  4. 使用 attr 进行检查

    $("#checkboxid").attr("checked")

i prefer second option.

我更喜欢第二种选择。