0

I am trying to change the radio button according to a value entered by a user.

So if the value is 4 or more, I need to change the radio button to check the value Yes. Else to check No.

Here is the script:

<td>a) Right <input type="text" class="form-control" style="width: 50px" name="right_result" id="right_result">/10 </td>
   <td style="vertical-align: middle">
   <input type="radio" class="radio-inline" name="monofilament_right_left" id="monofilament_right_left" value="Yes">Yes
   <input type="radio" class="radio" name="monofilament_right_left" id="monofilament_right_left" value="No">No
</td>

And the jQuery script:

$("#right_result").on('keyup', function(){
    var right_result = $("#right_result").val();
    //console.log(right_result)
    if(right_result>=4){
      $('input[id="monofilament_right_left"]:checked').val("Yes")
    }
})

The value is not changing when the user is adding the number in the text box.

I tried the solution

alim1990
  • 4,656
  • 12
  • 67
  • 130

2 Answers2

1

I've added some additional classes to select the radio buttons.

One thing to note is that IDs should be unique, you shouldn't use the same ID on two elements. That's why I've done this with classes.

This should work:

$("#right_result").on('keyup', function(){
    var right_result = $("#right_result").val();
    
    if(right_result>=4){
      $('.yes-value').prop('checked', true);
    } else if (right_result>0 && right_result<4) {
      $('.no-value').prop('checked', true);
    } else {
      $('.yes-value, .no-value').prop('checked', false)
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<td>a) Right <input type="text" class="form-control" style="width: 50px" name="right_result" id="right_result">/10 </td>
   <td style="vertical-align: middle">
   <input type="radio" class="radio-inline yes-value" name="monofilament_right_left" value="Yes">Yes
   <input type="radio" class="radio no-value" name="monofilament_right_left" value="No">No
</td>
1

Use different id for each radio like the following:

$("#right_result").on('keyup', function(){
    var right_result = $("#right_result").val();
    //console.log(right_result)
    if(right_result>=4){
      $('#monofilament_right_left1').prop("checked", true);
    }
    else{
      $('#monofilament_right_left2').prop("checked", true);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>a) Right <input type="text" class="form-control" style="width: 50px" name="right_result" id="right_result">/10 </td>
   <td style="vertical-align: middle">
   <input type="radio" class="radio-inline" name="monofilament_right_left" id="monofilament_right_left1" value="Yes">Yes
   <input type="radio" class="radio" name="monofilament_right_left" id="monofilament_right_left2" value="No">No
</td>
Mamun
  • 66,969
  • 9
  • 47
  • 59