簡體   English   中英

使用jQuery獲取checkbox的值為1/0

[英]Get value of checkbox as 1/0 with jQuery

我想用jQuery獲取所有輸入字段的值。 我可以用以下代碼來做到這一點。 但是,如果輸入字段是復選框,並且選中它,則它將返回“ on ”。 如果選中,如何將值設為1

jQuery的:

$('button').click(function() {

    inputs = $('.input');
    inputs.each(function() {
        var value = $(this).val();  
        alert(value);
    }); 

});

HTML:

<input type="text" class="input" />
<input type="text" class="input" />
<input type="checkbox" class="input">

<button>Get values<button>

演示: http //jsfiddle.net/yDKdT/

您需要檢查元素的類型是否相等checkbox

if( $( this ).attr( 'type' ) === 'checkbox' ) {
    value = +$(this).is( ':checked' );
}

提示: +符號將布爾值轉換為整數: 1/0

查看更新的jsFiddle

DEMO

var input = $('.input');

$('button').click(function() {

    input.each(function() {      
      var val = this.type=="checkbox" ? +this.checked : this.value ;      
      alert(  val  );
    }); 

});

什么是:

this.type=="checkbox" // Test if HTMLElement type is checkbox // (Boolean)
?
+this.checked // if true  // using '+', set boolean (true/false) to int (0/1)
:
this.value    // if false // just get the value
; 

附加讀數: 將布爾結果轉換為數字/整數

使用.is(':checked')而不是獲取值。 這將返回它作為布爾值,而不是如果選中“開”。

你可以試試這個。

$('button').click(function() {

    inputs = $('.input');
    inputs.each(function() {
        var value;
        if( $( this ).attr( 'type' ) === 'checkbox' ) {
            value = $(this).is( ':checked' ) ? 1: 0;
        }else
        {
            value = $(this).val();
        }
        alert(value);
    }); 

}); 

DEMO

 inputs.each(function () {
        if($(this).attr('type') == "checkbox") {
            value = $(this).prop('checked') == false ? 0: 1;
        }
        else {
        value = $(this).val();
        }
        alert(value);
    });

的jsfiddle

因為你沒有提到checkbox的任何值。試試這個:

<input type="checkbox" class="input" value="1">

演示: http //jsfiddle.net/yDKdT/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM