0

I was using this JavaScript code to make URL string, and worked good, but I added 3 radio buttons to the form and when the function runs it does not put in the string for the selected radio button, just adds it 3 times.

My JavaScript code is:

function MakeURL(){
var els = document.forms["Formulario"].elements;
 
 for (var i = 0, len = els.length; i < len; ++i) {
  if (els[i].tagName == "INPUT" || els[i].tagName == "SELECT") {
   if(i == (els.length - 1) ){
    todo += els[i].name + "=" + els[i].value.trim().replace(/\s\s+/g, ' ');
   }
   else{
    todo += els[i].name + "=" + els[i].value.trim().replace(/\s\s+/g, ' ')+ "&";
   }
  }
 }
}

The 3 radio buttons added are:

<input name="COLOR" id="Rojo" type="radio" value="red">
<input name="COLOR" id="Azul" type="radio" value="blue">
<input name="COLOR" id="Amarillo" type="radio" value="yellow"> 

And when the String is made, the restult for this radio buttons is:

COLOR=red&COLOR=blue&COLOR=yellow

but it should be only (if red is selected):

COLOR=red

Can anyone help me please?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
enmace
  • 23
  • 5
  • 1
    Check for the `checked` property – tymeJV Apr 08 '15 at 15:00
  • That's not true; the answer you offer is diferent, you need to know the name of the radio buttons, and i will never know it, coz in my form the radiobutons are created from MySQL using IDs and TIMESTAMP, so each group is impossible to leave fixed. – enmace Apr 08 '15 at 15:07
  • I'd recommend finding a library for this since your code is omitting several things that should be considered (textarea elements, disabled status, unchecked checkboxes). – Jack Dec 11 '15 at 01:00
  • But tymeJV is right, you should skip over elements that have a type value of 'checkbox' or 'radio' if their checked value isn't true. – Jack Dec 11 '15 at 01:02

0 Answers0