Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  18] [ 2]  / answers: 1 / hits: 24161  / 11 Years ago, tue, november 5, 2013, 12:00:00

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/


More From » jquery

 Answers
265

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


[#74497] Monday, November 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;