简体   繁体   中英

single id alerting same time in a while loop

I am having a table from where i am fetching activities and displaying in a table ...like this

<table width="1000px;" style="border:0px;" >
    <tr>
        <?php
            $sql_activities="select * from tb_activities";
            $query_activities=mysql_query($sql_activities);
            while($row_activities=mysql_fetch_array($query_activities))
            {
        ?>
        <td width="50">
            <input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="activities" onclick="hi() " id="activities" /><?php echo " ".$row_activities["activity_name"]; ?></td>
            <?php    
            } 
            ?>
    </tr>
</table>

Now i have applied it in an onlick event of a radio button and the script for the function is:

<script type="text/javascript">
function hi()
{
    a = document.getElementById("activities").value;
    alert(a);
}

</script>

i want to alert the name of the activity chosen but when i click on any activity, it shows the same. The first activity.ven if i have clicked on any other activity...can anyone help me ??

what you should do is change this:

onclick="hi()"

to this:

onclick="hi(this);

then your function would be:

function hi(who) {
    var a = who.value;
    alert(a);
}

In PHP side of things change:

<td width="50"><input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="activities" onclick="hi() " id="activities" /><?php echo " ".$row_activities["activity_name"]; ?></td>

To: ( YOU NEED Unique IDs on Input/ Radio Buttons to be generated dynamically & Sent to JS)

<?php $i = 1; ?>
<td width="50"><input type="radio" value="<?php echo $row_activities['activity_name']; ?>" name="<?php echo $row_activities['activity_name'].$i; ?>" id ="<?php echo $row_activities['activity_name'].$i; ?>" onclick="hi("<?php echo $row_activities['activity_name'].$i; ?> ")" /></td>
<?php $i++; ?>

In Javascript Change to This:

function hi(elementID) {
    var value = document.getElementById(elementID).value;
    alert(value);
}

Code may have some escape errors, but logically this should give you idea how to do it, Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM