Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 484
user2738640 Avatar asked Nov 05 '13 12:11

user2738640


People also ask

How do you get checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

Does checkbox have OnClick event?

The CheckBox has been assigned a JavaScript OnClick event handler. When the CheckBox is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether CheckBox is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.


2 Answers

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

like image 142
antyrat Avatar answered Oct 18 '22 20:10

antyrat


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

like image 43
Roko C. Buljan Avatar answered Oct 18 '22 19:10

Roko C. Buljan