namratha
namratha

Reputation: 672

Get value of radio button inside for loop

i am using for loop as below

<?php foreach($vtype as $vtypes) { ?>  
    <input type="radio" name="type" id="type<?php echo $vtypes['id'];?>" value="<?php echo $vtypes['id'];?>" />
<?php } ?>            

And in javascript i want to get the values of radio button clicked but everytime i click on radio button i am getting only the first value. my javascript code

<script type="text/javascript">
    var type = document.getElementById("type").value;
</script>        

Upvotes: 1

Views: 3465

Answers (3)

manhmaluc
manhmaluc

Reputation: 76

Please use it:

document.querySelector('input[name=type]:checked').value

Upvotes: 2

Nageen
Nageen

Reputation: 1759

<?php foreach($vtype as $key=> $vtypes)  { ?>  
    <input type="radio" name="type" id="type_<?php echo $key; ?>" value="<?php echo $vtypes['id'];?>" />

Here is javascript call

$(document).on("change","input[type=radio]",function(){
    var ac=$('[name="type"]:checked').val();
    alert(ac);
});

Upvotes: 0

Akhil Aravind
Akhil Aravind

Reputation: 6130

You can use this scenario. No matter how many checkbox you have

function getValue(data){
  alert(data.value)
}
<input type="radio" value="1" onclick="getValue(this)">
<input type="radio" value="2" onclick="getValue(this)">
<input type="radio" value="3" onclick="getValue(this)">

Upvotes: 0

Related Questions