如何检查jQuery中是否选中了复选框?

时间:2009-05-23 15:16:40

标签: jquery html dom checkbox

我需要检查复选框的checked属性,并使用jQuery基于checked属性执行操作。

例如,如果选中年龄复选框,则需要显示一个文本框以输入年龄,否则隐藏文本框。

但是以下代码默认返回false

if ($('#isAgeSelected').attr('checked'))
{
    $("#txtAge").show();
}
else
{
    $("#txtAge").hide();
}

如何成功查询checked属性?

66 个答案:

答案 0 :(得分:3269)

  

如何成功查询已检查的属性?

复选框DOM元素的checked属性将为您提供元素的checked状态。

鉴于您现有的代码,您可以这样做:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

然而,使用toggle

,有一种更漂亮的方法可以做到这一点

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>

答案 1 :(得分:1695)

使用jQuery的is()函数:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

答案 2 :(得分:514)

使用jQuery&gt; 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

使用新属性方法:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}

答案 3 :(得分:209)

jQuery 1.6 +

$('#isAgeSelected').prop('checked')

jQuery 1.5及以下

$('#isAgeSelected').attr('checked')

任何版本的jQuery

// Assuming an event handler on a checkbox
if (this.checked)

所有赠送金额都归Xian

答案 4 :(得分:155)

我正在使用这个,这非常正常:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

注意:如果选中该复选框,它将返回true,否则为未定义,因此最好检查“TRUE”值。

答案 5 :(得分:135)

使用:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

答案 6 :(得分:113)

从jQuery 1.6开始,jQuery.attr()的行为发生了变化,鼓励用户不要使用它来检索元素的检查状态。相反,您应该使用jQuery.prop()

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

另外两种可能性是:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")

答案 7 :(得分:90)

这对我有用:

$get("isAgeSelected ").checked == true

其中isAgeSelected是控件的ID。

另外,@ karim79的answer工作正常。我不确定在我测试时我错过了什么。

注意,这是答案使用Microsoft Ajax,而不是jQuery

答案 8 :(得分:84)

如果您使用的是jquery的更新版本,则必须使用.prop方法解决问题:

如果选中,则

$('#isAgeSelected').prop('checked')将返回true,如果未选中则会返回false。我确认了,我之前遇到过这个问题。 $('#isAgeSelected').attr('checked')$('#isAgeSelected').is('checked')正在返回undefined,这不是一个值得回答的情况。如下所示。

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

希望它有所帮助:) - 谢谢。

答案 9 :(得分:58)

对checkbox属性使用Click事件处理程序是不可靠的,因为checked属性可以在执行事件处理程序本身时更改!

理想情况下,您希望将代码放入change事件处理程序中,例如每次更改复选框的值时都会触发该事件处理程序(独立于如何完成)左右)。

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});

答案 10 :(得分:52)

使用:

<input type="checkbox" id="abc" value="UDB">UDB
<input type="checkbox" id="abc" value="Prasad">Prasad
$('input#abc').click(function(){
  if($(this).is(':checked'))
  {
    var checkedOne=$(this).val()
    alert(checkedOne);

    // Do some other action
  }
})

如果您希望仅在选中此复选框时才能执行必要的操作,这可能会有所帮助。

答案 11 :(得分:51)

我决定在没有jQuery的情况下发布关于如何做同样事情的答案。仅仅因为我是反叛者。

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

首先,您可以通过ID获取这两个元素。然后为复选框的onchange事件分配一个函数,该函数检查复选框是否已选中,并相应地设置年龄文本字段的hidden属性。在该示例中使用三元运算符。

以下是fiddle供您测试。

<强>附录

如果跨浏览器兼容性存在问题,那么我建议将CSS display属性设置为 none inline

elem.style.display = this.checked ? 'inline' : 'none';

较慢但跨浏览器兼容。

答案 12 :(得分:45)

我相信你可以这样做:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}

答案 13 :(得分:43)

有很多方法可以检查是否选中了复选框:

使用jQuery检查的方法

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

检查示例或文档:

答案 14 :(得分:41)

我遇到了完全相同的问题。我有一个ASP.NET复选框

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

在jQuery代码中,我使用以下选择器来检查是否选中了复选框,它似乎像魅力一样。

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

我确信您也可以使用ID代替CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

我希望这会对你有所帮助。

答案 15 :(得分:39)

这对我有用:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});

答案 16 :(得分:34)

使用此:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

如果选中该复选框,则长度大于零。

答案 17 :(得分:33)

您可以使用此代码:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

答案 18 :(得分:32)

我这样做的方法是:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}

答案 19 :(得分:31)

$(selector).attr('checked') !== undefined

如果输入被选中,则返回true,如果不是,则返回false

答案 20 :(得分:30)

您可以使用:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();
if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

他们两个都应该工作。

答案 21 :(得分:30)

$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});

答案 22 :(得分:25)

1)如果您的HTML标记是:

<input type="checkbox"  />
使用

attr:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

如果使用道具:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2)如果您的HTML标记是:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"
使用

attr:

$(element).attr("checked") // Will return checked whether it is checked="true"

使用的道具:

$(element).prop("checked") // Will return true whether checked="checked"

答案 23 :(得分:24)

此示例适用于按钮。

尝试以下方法:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});

答案 24 :(得分:24)

最佳答案并不适合我。这确实如此:

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

基本上,当单击元素#li_13时,它会检查是否使用.attr('checked')函数检查了元素#agree(哪个是复选框)。如果它然后fadeIn #saveForm元素,如果没有fadeOut saveForm元素。

答案 25 :(得分:21)

虽然您已针对您的问题提出了JavaScript解决方案(在textboxcheckbox时显示checked),但此问题可以通过css解决 。使用此方法,您的表单适用于已禁用JavaScript的用户。

假设您有以下HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

您可以使用以下CSS来实现所需的功能:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

对于其他场景,您可能会想到合适的CSS选择器。

Here is a Fiddle to demonstrate this approach

答案 26 :(得分:21)

切换:0/1或者

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});

答案 27 :(得分:21)

我正在使用它:

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

答案 28 :(得分:18)

我认为这将是一个简单的

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    picker.dismissViewControllerAnimated(true, completion: { () in
        if (picker.sourceType == .PhotoLibrary) {
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            let library = ALAssetsLibrary()
            var url: NSURL = info[UIImagePickerControllerReferenceURL] as! NSURL

            library.assetForURL(url, resultBlock: { (asset: ALAsset!) in
                    if asset.valueForProperty(ALAssetPropertyLocation) != nil {
                        let latitude = (asset.valueForProperty(ALAssetPropertyLocation) as! CLLocation!).coordinate.latitude
                        let longitude = (asset.valueForProperty(ALAssetPropertyLocation) as! CLLocation!).coordinate.longitude
                        println("\(latitude), \(longitude)")
                    }
                },
                failureBlock: { (error: NSError!) in
                    println(error.localizedDescription)
                })
        }
    })
}

答案 29 :(得分:17)

if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}

答案 30 :(得分:17)

我确定这不是一些启示,但我没有在一个例子中看到这一切:

所有选中复选框的选择器(在页面上):

$('input[type=checkbox]:checked')

答案 31 :(得分:16)

从本地文件系统包含jQuery。我使用了Google的CDN,还有很多CDN可供选择。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

单击mycheck类中的复选框后,代码将立即执行。如果选中当前单击的复选框,则会禁用所有其他复选框并启用当前复选框。如果未选中当前的那个,它将再次启用所有复选框以进行重新检查。

<script type="text/javascript">
    $(document).ready(function() {

        var checkbox_selector = '.mycheck input[type=checkbox]';

        $(checkbox_selector).click(function() {
            if ($($(this)).is(':checked')) {

                // Disable all checkboxes
                $(checkbox_selector).attr('disabled', 'disabled');

                // Enable current one
                $($(this)).removeAttr('disabled');
            }
            else {
                // If unchecked open all checkbox
                $(checkbox_selector).removeAttr('disabled');
            }
        });
    });
</script>

简单的测试形式

<form method="post" action="">
    <div class="mycheck">
        <input type="checkbox" value="1" /> Television
        <input type="checkbox" value="2" /> Computer
        <input type="checkbox" value="3" /> Laptop
        <input type="checkbox" value="4" /> Camera
        <input type="checkbox" value="5" /> Music Systems
    </div>
</form>

输出屏幕:

Enter image description here

答案 32 :(得分:15)

我在Firefox 9.0.1中验证了以下内容可用于捕获更改后的复选框状态:

$("#mycheckbox").change(function() {
    var value = $(this).prop("checked") ? 'true' : 'false';                     
    alert(value);
});

答案 33 :(得分:15)

checked的{​​{1}}属性与input type="checkbox"属性映射,defaultChecked属性。

因此,如果在取消选中复选框时在页面中执行某些操作,请改用checked方法。它获取属性值并随着复选框状态的变化而更改。

在这些情况下,

使用prop())或attr((在纯JavaScript中)并不是正确的做事方式。

如果getAttribute是相关复选框,则执行以下操作以获取值:

elem

elem.checked

答案 34 :(得分:13)

自动

$(document).ready(function()
{
    $('#isAgeSelected').change(function()
    {
        alert( 'value =' + $('#chkSelect').attr('checked') );
    });
});

HTML

<b> <input type="isAgeSelected" id="chkSelect" /> Age Check </b>

<br/><br/>

<input type="button" id="btnCheck" value="check" />

的jQuery

$(document).ready(function()
{
    $('#btnCheck').click(function()
    {
        var isChecked = $('#isAgeSelected').attr('checked');

        if (isChecked == 'checked')
            alert('check-box is checked');
        else
            alert('check-box is not checked');
    })
});

<强>的Ajax

function check()
{
    if (isAgeSelected())
        alert('check-box is checked');
    else
        alert('check-box is not checked');
}

function isAgeSelected()
{
    return ($get("isAgeSelected").checked == true);
}

答案 35 :(得分:12)

这是一个示例,其中包含初始化显示/隐藏以匹配页面加载时的复选框状态;在刷新页面时考虑到firefox 记住复选框状态的事实,但不会记住显示/隐藏元素的状态。

$(function() {
    // initialise visibility when page is loaded
    $('tr.invoiceItemRow').toggle($('#showInvoiceItems').attr('checked'));
    // attach click handler to checkbox
    $('#showInvoiceItems').click(function(){ $('tr.invoiceItemRow').toggle(this.checked);})
});

(在此问题的其他答案的帮助下)

答案 36 :(得分:12)

这是我认为我需要有效执行此类操作的最少量代码。我发现这种方法很有用;它返回一个选中的复选框数组,然后你可以使用它们的值(这个解决方案使用jQuery):

// This is how you get them
var output = "";
var checkedBoxes = $("DivCheckBoxesAreIn").children("input:checked");
if(checkedBoxes.length <= 0) {
    alert('Please select check boxes');
    return false;
};

// And this is how you use them:
checkedBoxes.each(function() {
    output +=  this.value + ", ";
};

打印“输出”将为您提供以逗号分隔的值列表。

答案 37 :(得分:12)

我遇到了同样的问题,并且没有任何发布的解决方案似乎工作,然后我发现这是因为ASP.NET将CheckBox控件呈现为内置INPUT的SPAN,因此CheckBox ID实际上是一个ID SPAN,而不是INPUT,所以你应该使用:

$('#isAgeSelected input')

而不是

$('#isAgeSelected')

然后上面列出的所有方法都应该有用。

答案 38 :(得分:10)

$(document).on("click","#isAgeSelected",function(){
  if($(this).prop("checked") == true){
    $("#txtAge").show();
  }
  else if($(this).prop("checked") == false){
    $("#txtAge").hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <input type="checkbox" id="isAgeSelected"/>

<div id="txtAge" style="display:none">
<input type="text" name="age" placeholder="Please enter age" />
</div>

答案 39 :(得分:10)

像下面一样简单地使用它

 $('#isAgeSelected').change(function() {
     if ($(this).is(":checked")) { // or if($("#isAgeSelected").attr('checked') == true){
         $('#txtAge').show();
     } else {
         $('#txtAge').hide();
     }
 });

答案 40 :(得分:10)

这是我的解决方法:

$('#vcGoButton').click(function () {
    var buttonStatus = $('#vcChangeLocation').prop('checked');
    console.log("Status is " + buttonStatus);
    if (buttonStatus) {
        var address = $('#vcNewLocation').val();
        var cabNumber = $('#vcVehicleNumber').val();
        $.get('postCabLocation.php',
              {address: address, cabNumber: cabNumber},
              function(data) {
                  console.log("Changed vehicle " + cabNumber + " location to " + address );
              });
    }
    else {
        console.log("VC go button clicked, but no location action");
    }
});

答案 41 :(得分:9)

设置器:

$("#chkmyElement")[0].checked = true;

吸气剂:

if($("#chkmyElement")[0].checked) {
   alert("enabled");
} else {
   alert("disabled");
}

答案 42 :(得分:9)

使用纯 JavaScript

input

答案 43 :(得分:9)

使用:

$(this).toggle($("input:checkbox", $(this))[0].checked);

当您选择脱离上下文时,请记住您需要[0]才能访问该复选框。

答案 44 :(得分:8)

我实际上会优先考虑change事件。

$('#isAgeSelected').change(function() {
    $("#txtAge").toggle(this.checked);
});

Demo Fiddle

答案 45 :(得分:8)

试试这个,

$('#isAgeSelected').click(function() {
    if(this.checked){
        $("#txtAge").show();
    } else{
        $("#txtAge").hide();
    } 
});

答案 46 :(得分:7)

选择器返回多个对象,它必须采用数组中的第一项:

// Collection
var chckremember = $("#chckremember");


// Result boolen
var ischecked=chckremember[0].checked;

答案 47 :(得分:7)

我正在使用jQuery 1.11.1,我在设置和阅读复选框值方面遇到了麻烦。

我终于通过这两个功能解决了这个问题:

function setCheckboxValue(checkBoxId, checked) {
    if (checkBoxId && (checked === true || checked === false)) {
        var elem = $('#' + checkBoxId);
        if (checked === true) {
            elem.attr('checked', 'checked');
        } else {
            elem.removeAttr('checked');
        }
    }
}

function isChecked(checkBoxId) {
    return $('#' + checkBoxId).attr('checked') != null;
}

它可能看起来有点脏,但它解决了我在不同类型的浏览器中遇到的所有有线问题。

答案 48 :(得分:6)

if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

答案 49 :(得分:4)

这个解决方案怎么样?

$("#txtAge")[
    $("#isAgeSelected").is(':checked') ?
    'show' :
    'hide'
]();

答案 50 :(得分:4)

  

您可以尝试更改复选框的事件

$("#isAgeSelected").on('change',function(){
    if($("#isAgeSelected").is(':checked'))
        alert("checked");  
    else{
         alert("unchecked");  
    }
});

答案 51 :(得分:4)

您可以尝试以下代码:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});

答案 52 :(得分:3)

我需要检查复选框的选中属性,并使用jQuery根据选中的属性执行操作。

E.X-

1)如果选中了年龄复选框,则在加载时运行以获取复选框值,那么我需要显示一个文本框以输入年龄,否则隐藏该文本框。

2)如果选中了年龄复选框,那么我需要显示一个文本框来输入年龄,否则使用复选框的单击事件来隐藏该文本框。

因此默认情况下,代码不会返回false:

尝试以下操作:

<html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </head>
        <body>
            <h1>Jquery Demo</h1>
            <input type="checkbox" name="isAge" checked id="isAge"> isAge <br/>
            <div id="Age" style="display:none">
              <label>Enter your age</label>
              <input type="number" name="age">
            </div>
            <script type="text/javascript">
            if(document.getElementById('isAge').checked) {
                $('#Age').show();
            } else {
                $('#Age').hide();
            }   
            $('#isAge').click(function() {
                if(document.getElementById('isAge').checked) {
                    $('#Age').show();
                } else {
                    $('#Age').hide();
                }
            }); 
            </script>
        </body>
    </html>

这是修改后的版本:https://jsfiddle.net/sedhal/0hygLtrz/7/

答案 53 :(得分:2)

对于旧版本的jQuery,我不得不使用以下内容,

$('#change_plan').live('click', function() {
     var checked = $('#change_plan').attr('checked');
     if(checked) {
          //Code       
     }
     else {
          //Code       
     }
});

答案 54 :(得分:2)

if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

答案 55 :(得分:2)

如果您需要知道是否以纯javascript选中了复选框,则应使用此代码。

let checkbox =document.getElementById('myCheckboxId');
if(checkbox.checked) {
    alert("element is checked");
} else {
    alert("element is  ot checked");
}

答案 56 :(得分:2)

在纯js中,复选框状态更易于阅读

isAgeSelected.checked

function check() {
  txtAge.style.display= isAgeSelected.checked ? 'block':'none';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Age <input type="checkbox" id="isAgeSelected"/>

<button onclick="check()">Check</button>

<div id="txtAge" style="display:none">
Age is selected
</div>

答案 57 :(得分:1)

jQuery prop() 方法提供了一种简单、有效且可靠的方法来跟踪复选框的当前状态。它在所有条件下都能很好地工作,因为每个复选框都有一个 checked 属性,用于指定其选中或未选中状态。

不要误解为checked属性。 checked 属性只定义了复选框的初始状态,而不是当前状态。让我们看看它是如何工作的:

<script>
    $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            if($(this).prop("checked") == true){
                console.log("Checkbox is checked.");
            }
            else if($(this).prop("checked") == false){
                console.log("Checkbox is unchecked.");
            }
        });
    });
</script>

详细说明:jQuery prop()

但是,您也可以使用 jQuery 的 is() 函数

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // Age is selected - Show the Age
else
    $("#txtAge").hide();  // Age is not selected - Hide the Age

答案 58 :(得分:1)

如果您需要使用CSS类作为jQuery选择器,您可以执行以下操作:

$(document).ready(function () {
        $('.myOptionCheckbox').change(function () {            
            if ($(this).prop('checked') == true) {
                console.log("checked");           
            }
            else {
                console.log("unchecked");                
            }
        });
    });

它也适用于checkboxesradioboxes

答案 59 :(得分:1)

要对单击时处于选中状态或未选中状态的复选框执行操作。

<input type="checkbox" id="customCheck1">

 $('#customCheck1').click(function () {
        if (this.checked == true) {
            console.log('checked');
        }
        else {
            console.log('un-checked');
        }
    });

答案 60 :(得分:1)

此功能是另类且稳定的:

$('#isAgeSelected').context.checked
(return True/False)

示例:

if($('#isAgeSelected').context.checked){ //if Checkbox is checked then bla bla..
    /*.....*/
}else{
    /*.....*/
}

答案 61 :(得分:1)

D:\HYBRIS Soft copies\hybris\bin\platform>ant clean all


Buildfile: D:\HYBRIS Soft copies\hybris\bin\platform\build.xml

[echo] D:\HYBRIS Soft copies\hybris\bin\platform/tomcat/bin

[mkdir] Created dir: D:\HYBRIS Soft copies\hybris\log

[mkdir] Created dir: D:\HYBRIS Soft copies\hybris\data

[mkdir] Created dir: D:\HYBRIS Soft copies\hybris\temp\hybris

[input]

[input]  **** NO CONFIG FOLDER FOUND ****

[input]

[input]  No config folder was found at D:\HYBRIS Soft copies\hybris\config.

[input]  A "fresh" folder containing basic configuration files and the hybris

[input]  demo licence will be created for your convenience.

[input]  Please adjust and review the configuration files (and license) and

[input]  call 'ant' again. This directory will never be overridden or

[input]  touched again. Always use this configuration folder for configuration

[input]  of platform, do not change anything within the platform folder.

[input]

[input]  Please choose the configuration template.

[input]  Press [Enter] to use the default value ([develop], production)

[copy] Copying 26 files to D:\HYBRIS Soft copies\hybris\config

[copy] Copying 1 file to D:\HYBRIS Soft copies\hybris\config

[ysetplatformproperties] Web root <web> of the extension <testweb> has been explicitely disabled


[ysetplatformproperties] java.util.Objects.requireNonNull(Ljava/lang/Object;)Ljava/lang/Object;

[ysetplatformproperties] java.lang.NoSuchMethodError: java.util.Objects.requireNonNull(Ljava/lang/Object;)L
g/Object;

[ysetplatformproperties] at de.hybris.ant.taskdefs.internal.context.TomcatContext$SimpleElement.<ini
tContext.java:222)

[ysetplatformproperties] at de.hybris.ant.taskdefs.internal.context.TomcatContext$SimpleElement.<ini
tContext.java:220)

[ysetplatformproperties] at de.hybris.ant.taskdefs.internal.context.TomcatContext.<init>(TomcatConte
81)

[ysetplatformproperties] at de.hybris.ant.taskdefs.SetPlatformProperties.createTomcatContext(SetPlat
erties.java:623)

[ysetplatformproperties] at de.hybris.ant.taskdefs.SetPlatformProperties.setAllProperties(SetPlatfor
ies.java:494)

[ysetplatformproperties] at de.hybris.ant.taskdefs.SetPlatformProperties.execute(SetPlatformProperti
117)

[ysetplatformproperties] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)

[ysetplatformproperties] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)

[ysetplatformproperties] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessor
a:43)

[ysetplatformproperties] at java.lang.reflect.Method.invoke(Method.java:613)

[ysetplatformproperties] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:1

[ysetplatformproperties] at org.apache.tools.ant.Task.perform(Task.java:348)

[ysetplatformproperties] at org.apache.tools.ant.Target.execute(Target.java:435)

[ysetplatformproperties] at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:168

[ysetplatformproperties] at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:

[ysetplatformproperties] at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:162)

[ysetplatformproperties] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)

[ysetplatformproperties] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

[ysetplatformproperties] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.jav

[ysetplatformproperties] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessor
a:43)

[ysetplatformproperties] at java.lang.reflect.Method.invoke(Method.java:613)

[ysetplatformproperties] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:1

[ysetplatformproperties] at org.apache.tools.ant.Task.perform(Task.java:348)

[ysetplatformproperties] at org.apache.tools.ant.Target.execute(Target.java:435)

[ysetplatformproperties] at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:179

[ysetplatformproperties] at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:9

[ysetplatformproperties] at org.apache.tools.ant.Main.runBuild(Main.java:826)

[ysetplatformproperties] at org.apache.tools.ant.Main.startAnt(Main.java:235)

[ysetplatformproperties] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)

[ysetplatformproperties] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

BUILD FAILED

D:\HYBRIS Soft copies\hybris\bin\platform\build.xml:20: The following error occurred while executing this l

D:\HYBRIS Soft copies\hybris\bin\platform\resources\ant\antmacros.xml:114: java.lang.NoSuchMethodError: jav
bjects.requireNonNull (Ljava/lang/Object;)Ljava/lang/Object;

 at de.hybris.ant.taskdefs.internal.context.TomcatContext$SimpleElement.<init>(TomcatContext.java:22

at de.hybris.ant.taskdefs.internal.context.TomcatContext$SimpleElement.<init>(TomcatContext.java:22

at de.hybris.ant.taskdefs.internal.context.TomcatContext.<init>(TomcatContext.java:81)
at de.hybris.ant.taskdefs.SetPlatformProperties.createTomcatContext(SetPlatformProperties.java:623) 

at de.hybris.ant.taskdefs.SetPlatformProperties.setAllProperties(SetPlatformProperties.java:494)

at de.hybris.ant.taskdefs.SetPlatformProperties.execute(SetPlatformProperties.java:117)

at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)

at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:613)

at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106  

at org.apache.tools.ant.Task.perform(Task.java:348) 

at org.apache.tools.ant.Target.execute(Target.java:435) 

at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:168) 

at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:230) 

at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:162) 

at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292) 

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 

at java.lang.reflect.Method.invoke(Method.java:613) 

at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) 

at org.apache.tools.ant.Task.perform(Task.java:348) 

at org.apache.tools.ant.Target.execute(Target.java:435) 

at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:179) 

at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:93) 

at org.apache.tools.ant.Main.runBuild(Main.java:826) 

at org.apache.tools.ant.Main.startAnt(Main.java:235) 

at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280) 

at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109) 

Total time: 27 seconds

答案 62 :(得分:0)

请尝试下面的代码来检查复选框是否已选中

$(document).ready(function(){

$("#isAgeSelected").on('change',function(){

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else{
    $("#txtAge").hide();  // unchecked
}

});

});

答案 63 :(得分:0)

if($('#isAgeSelected').prop('checked')) {
    // do your action 
}

答案 64 :(得分:-1)

$("#isAgeSelected").prop('checked', true);

答案 65 :(得分:-2)

嗨,您可以使用普通的var stripe = require('stripe')('sk_test_...'); const paymentMethod = await stripe.paymentMethods.create('card',cardElementObj.card); ,如下所示:

Javascript
document.getElementById('checkboxOption').addEventListener('click',      
   event => console.log(event.target.checked)
);