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/
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With