Skip to content
Advertisement

Form – checklist value to not transferred to PHP

I’m trying to populate the multiple selected choice from checklist into PHP. However, only the “Reading” choice is populating in the new window and not the other choices that I have selected. For example, I have selected “Painting & Travelling” but after I clicked submit, the value that showing is “Reading”.Kindly advise how to fix this. Thanks in advance. I’m new to web development.

Javascript

function validate(){


   var x3=document.getElementById("hobbies");


   if (x3.value == "") 

   {
      alert("No blank values allowed")
      return false;
   }
   else
   {

      window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+x3.value+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}

Form

<form onsubmit="return validate()" method= "get">



<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading"/>Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting"/>Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling"/>Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking"/>Baking<br/><br/>


  </div>

</form>

Advertisement

Answer

Please try the following:

<form onsubmit="return validate()" method= "get">
    <label>Hobbies : </label><br><br>
    <input type="checkbox" id="hobbies" name="hobbies[]" value="Reading" />Reading<br/>
    <input type="checkbox" id="hobbies" name="hobbies[]" value="Painting" />Painting<br/>
    <input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling" />Traveling<br/>
    <input type="checkbox" id="hobbies" name="hobbies[]" value="Baking" />Baking<br/><br/>
    <input type="submit" value="Submit" />
</form>

<script type="text/javascript">
    function validate() {
      var x3 = document.getElementsByName("hobbies[]");
      var selectedVals = "";

      for(var i = 0; i < x3.length; i++) {
        if((x3[i].checked) && (x3[i].value != '')) {
            selectedVals += (selectedVals == '')?x3[i].value:','+x3[i].value;
          }
      }

      if(selectedVals == "") {
        alert("No blank values allowed")
        return false;
      }
      else {
        window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+selectedVals+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
      }
    }
</script>

Hope this may help.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement