-1

I have 2 input types which are both check boxes. I am trying to get the value of them but it says it is 'undefined'.

<tr>
  <td>
    <input type='checkbox' class='gymyears'>
    Yes
    <input type='checkbox' class='gymyears'>
    No
  </td>
</tr>

var Gymyearsv = $(".gymyears").val();
Christheoreo
  • 373
  • 3
  • 15
Waqz
  • 9
  • 4

1 Answers1

0

The problem is that your checkboxes have'nt a value, thats why its still undefined. You have to look for 'checked' instead:

var Gymyearsv = $(".gymyears");

function getState() {
  Gymyearsv.each(function(i, checkbox) {
    console.log(checkbox.checked);
  });
}

// or use $('#yourID').is(":checked");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <input type='checkbox' class='gymyears'> Yes
    <input type='checkbox' class='gymyears'> No
  </td>
</tr>
<button onclick="getState();">get state</button>

Or as Roy mentioned you could use radios instead:

function getState(){
  console.log($("input[name=gymyears]:checked").val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <input type='radio' name='gymyears' value="yes"> Yes
    <input type='radio' name='gymyears' value="no"> No
  </td>
</tr>
<button onclick="getState();">get state</button>
jsadev.net
  • 2,800
  • 1
  • 16
  • 28