简体   繁体   中英

Get value of checkbox as 1/0 with jQuery

I want to get values of all input fields with jQuery. I can do that with following code. However if the input field is checkbox, and it is checked, it will return " on ". How can I get the value as 1 if checked?

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>

Demo: http://jsfiddle.net/yDKdT/

You need to check if type of your element is equal checkbox :

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

Tip: + symbol will convert Boolean values into Integers: 1/0

See updated jsFiddle

DEMO

var input = $('.input');

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

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

});

What is does:

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
; 

Additional reading: Convert boolean result into number/integer

Use .is(':checked') instead of getting the value. This will return it as a boolean instead of getting "on" if checked.

You can try this .

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

Because you have not mentioned any value for checkbox.Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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