0

I would like to put an onclick="myfunction()" or any event that will bring the value of the Radio Input. The value would need to be display as soon as its chosen with ajax. Same with all the other values. The problem is that the Radio Input is displayed by a "for" so that it displays as many times as there is data (colors in this case) in the api. What should I do?

$('input:radio[name=color]').change(function()

This kind of works, but only in the html file, not the .js file. In addition, it doesn't correctly get me the other values (position & alto, etc..)

PHP:

for ($quantity=0;$quantity<$numberofcolors;$quantity++)
{
$vartest=$data[$testcontador]["Colores"][$quantity];
echo '<div class="hiddenradio"><label><input type="radio" id="color" required class="stored" name="color" value="'.$vartest.'" />
<img style="border: 2px solid black; width: 50px;margin:5px;" src="../imagenes/'.  $vartest.'.png"/> '.$vartest.'</label></div>
';
//this displays all color icons.
}
echo '<label for="name">Alto: </label>
<span>
  <input type="number" id="alto" min="'.$altomin.'" max="'.$altomax.'" onkeyup="myfunction()" name="alto" value="'.$altomin.'" class="required" role="input" aria-required="true" required/>
</span>';

JS:

 function myfunction() {
  var posit = document.getElementById("position").value;
  var alto = document.getElementById("alto").value;
$.ajax({
     url: "../vista/gethint.php",
     type: "GET",
     data: {altojs: alto,positjs:posit},
     success: function(data){
            document.getElementById("icard3").innerHTML = data;
     }
  });
}

 var alto = document.getElementById("alto").value;

I want something like this but for the radio input so it's simpler to get the value. I'm new at this stuff...

Neo Chen
  • 1
  • 1
  • You'd need to attach the listener to the body, then target the element. – Adam Feb 05 '19 at 20:26
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Adam Feb 05 '19 at 20:26
  • Give all of the elements that you want to behave the same way the same class. Then bind the event handler to the class. Also, don't assign a static element ID within a loop (such as `id="color"`). All elements must have unique IDs (or no ID) – Patrick Q Feb 05 '19 at 20:26
  • ...and use the "checked" property to pick the right one... const radioButtons = document.querySelector(".classOnYourRadioButtons"); for(let i = 0; i < radioButtons.length; i++){ if(radioButtons[i].checked){ alert(radioButtons[i].value); }} – Cat Feb 05 '19 at 20:36
  • 1
    Give them a `class="stored color"` instead of equal `id`s. Use array names `name=color[$quantity]`. Do not echo HTML, write plain HTML closing PHP tags. – Pinke Helga Feb 05 '19 at 20:39
  • I was able to fix it using this: var radioButTrat = document.getElementsByName("color"); for (var i=0; i – Neo Chen Feb 05 '19 at 22:00

0 Answers0