12

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/

user2738640
  • 1,207
  • 8
  • 23
  • 34

6 Answers6

35

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

antyrat
  • 27,479
  • 9
  • 75
  • 76
4

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

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

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

Halaster
  • 1,442
  • 1
  • 17
  • 27
1

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

sudhansu63
  • 6,025
  • 4
  • 39
  • 52
1
 inputs.each(function () {
        if($(this).attr('type') == "checkbox") {
            value = $(this).prop('checked') == false ? 0: 1;
        }
        else {
        value = $(this).val();
        }
        alert(value);
    });

JSFiddle

Praveen
  • 55,303
  • 33
  • 133
  • 164
0

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

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

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

Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22