Search code examples
javascripthtmlradio-buttonhtml-tableprototypejs

Get table row based on radio button using prototype/Javascript


I have an html table that has a name and a radio button like so:

<table id="cars">
  <thead>
    <tr>
      <th>Car Name</th>
      <th></th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td class="car">Ford Focus</td>
      <td><input type="radio" id="selectedCar" name="selectedCar" value="8398"></td>
    </tr>

    <tr>
      <td class="car">Lincoln Navigator</td>
      <td><input type="radio" id="selectedCar" name="selectedCar" value="2994"></td>
    </tr>

  </tbody>
</table>
<input type="button" value="Select Car" onclick="selectCar()"></input>

I want to be able to select a radio button, then click another button and get the value of the radio button (which is a unique ID) as well as the car name text (like Ford Focus). How should I code the selectCar method? I've tried a few things like:

val1 = $('tr input[name=selectedCar]:checked').parent().find('#cars').html();
val1 = $("td input[name='selectedCar']:checked").parents().find('.cars').html();
val1 = $('selectedCar').checked;

but I can't get the proper values.

I'm using prototype, but the solution can be plain Javascript as well.


Solution

  • All IDs have to be unique!

    You can try with this HTML:

    <tr>
      <td class="car">Ford Focus</td>
      <td><input type="radio" id="selectedCar1" name="selectedCar" value="8398"></td>
    </tr>
    
    <tr>
      <td class="car">Lincoln Navigator</td>
      <td><input type="radio" id="selectedCar2" name="selectedCar" value="2994"></td>
    </tr>
    

    After this, you can test using:

    val1 = $('selectedCar1').checked;
    

    (returns true or false).

    Or, if you want to grab the selected value, use getElementsByName:

    function getCarValue()
    {
        var theCars = document.getElementsByName("selectedCar");
        var i = theCars.length;
        while (i--) {
            if(theCars[i].checked)
                 return theCars[i].value;
    
        }
    }