0

I want to use either Javascript or JQuery to get the value of a checkbox when it is checked.

How can I do that? Please see question marks in the JQuery code below.

<html>
<body>

<form id="toggleForm" action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

<script>
$('**???**').on('**checked???**', function(){
   var checkedValue = $(this).attr('**value???**');
   console.log("The checkbox value property is "+checkedValue);
});
</script>

</body>
</html>

(Please note that my question is not a duplicate of other questions, because in the other questions, the checkboxes have a class and the code is grabbing them using their class. In my question, my checkboxes don't have a class. How can I grab them without them having a class or ID?? How can I check their value? What is the event called for when they are checked? Please see the question marks in my attempt above.)

big picture
  • 301
  • 6
  • 14

3 Answers3

1
  1. Use .val()

$(':checkbox').on('change', function() {

  var checkedValue = $(this).val();
  console.log("The checkbox value property is " + checkedValue);


})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggleForm" action="">
  <input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car">I have a car
</form>
guradio
  • 15,524
  • 4
  • 36
  • 57
1

$(document).on('change','input:checkbox',function(){
var value=$(this).val();
if($(this).is(':checked')){
alert(value+" selected");
}
else{
alert(value+" unselected");}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>

<form id="toggleForm" action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

</body>
</html>
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

$(document).ready(function(){
$('input:checkbox').change(function(){
($(this).prop("checked") == true) ? 
console.log($(this).val()+ " " +"checked"):console.log($(this).val()+ " " +"unchecked")
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggleForm" action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>
vicky patel
  • 699
  • 2
  • 8
  • 14