subhra subhra - 4 months ago 8
HTML Question

Failed to check radio button as per value and need to validate using Javascript/Jquery

I need one help. I need to check radio button as per value by taking the id and validate those using Javascript/Jquery. I am explaining my code below.

<div>
<input type="radio" name="rd0" value="57db18">Raj
<input type="radio" name="rd0" value="57da17">Rahul
<input type="radio" name="rd0" value="57db19">Mona
</div>
<br>
<br>
<div>
<input type="radio" name="rd1" value="57db18">A
<input type="radio" name="rd1" value="57da17">B
<input type="radio" name="rd1" value="57db19">C

</div>
<br>
<br>
<div >
<input type="radio" name="rd2" value="57db18">Apple
<input type="radio" name="rd2" value="57da17">Orange
<input type="radio" name="rd2" value="57db19">Mango

</div>
<span>
<button type="button" id="btn" name="btn" onclick="setValue()">Set</button>
</span>
<span>
<button type="button" id="vbtn" name="vbtn" onclick="validateRadioButtonValue()">Validate</button>
</span>


Here i have 3 set of radio button and when user will click on
set
button the radio button should check as per given value in a loop. the scripting part is given below.

var valu = ['57da17', '57db18', '57db19'];
function setValue(){
for(var i=0;i<valu.length;i++){
$('#rd'+i+'[value="' + valu[i]+ '"]').prop('checked', true);
console.log('checked btn',$('#rd'+i).is(':checked') );
}
}


but in this current case its not happening .When user will also click on
validate
button ,it should verify all radio button is checked or not.Please help me.

Answer

Try this :

$('input[name=rd'+i+'][value="' + valu[i]+ '"]').prop('checked', true)

var valu = ['57da17', '57db18', '57db19'];
function setValue(){
    for(var i=0;i<valu.length;i++){
         
      $('input[name=rd'+i+'][value="' + valu[i]+ '"]').prop('checked', true);
         console.log('checked btn',$('input[name=rd' + i + ']').is(':checked') );
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="radio" name="rd0"  value="57db18">Raj
  <input type="radio" name="rd0"  value="57da17">Rahul
  <input type="radio" name="rd0"  value="57db19">Mona
</div>
<br>
<br>
<div>
  <input type="radio" name="rd1"  value="57db18">A
  <input type="radio" name="rd1"  value="57da17">B
  <input type="radio" name="rd1"  value="57db19">C

</div>
<br>
<br>
<div >
  <input type="radio" name="rd2"  value="57db18">Apple
  <input type="radio" name="rd2"  value="57da17">Orange
  <input type="radio" name="rd2"  value="57db19">Mango

</div>
    <span>
      <button type="button" id="btn" name="btn" onclick="setValue()">Set</button>
    </span>
    <span>
      <button type="button" id="vbtn" name="vbtn" onclick="validateRadioButtonValue()">Validate</button>
    </span>