0

I have created the dropdown list in my index page i want to select the one value from that list and validate it if not selected any value the code for that.

<script>
function Validate() {
    var b = document.getElementById("etnik");
    var strUser = b.options[b.selectedIndex].value;
    var strUser1 = b.options[b.selectedIndex].text;
    if (strUser == 0) {
        alert("Sila isikan ruangan yang kosong.");
    }
}

function Validate1() {
    var a = document.getElementById("Jantina");
    var strUser = a.options[a.selectedIndex].value;
    var strUser1 = a.options[a.selectedIndex].text;
    if (strUser == 0) {
        alert("Sila isikan ruangan yang kosong.");
    }
}

function Validate2() {
    var c = document.getElementById("warganegara");
    var strUser = c.options[c.selectedIndex].value;
    var strUser1 = c.options[c.selectedIndex].text;
    if (strUser == 0) {
        alert("Sila isikan ruangan yang kosong.");
    }
}
</script>
<body>
   <form>
      <select id="Jantina" name="Jantina">
         <option value='0'>Sila Pilih</option>
         <option value='1'>Lelaki</option>
         <option value='2'>Perempuan</option>
      </select>
      <br>
      <select id="etnik" name="etnik">
         <option value='0'>Sila Pilih</option>
         <option value='1'>Melayu</option>
         <option value='2'>India</option>
      </select>
      <br>
      <select id="warganegara" name="warganegara">
         <option value='0'>Sila Pilih</option>
         <option value='1'>Yes</option>
         <option value='2'>Tidak</option>
      </select>
      <input name="Simpan" type="submit" value="Simpan" onClick="Validate()" onclick="Validate1()" onclick="Validate2()">
   </form>
</body>

But i dont know how to make this to loop version. It will be pleasure for the help and idea. TY (sorry for bad in english)

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
eRedz
  • 13
  • 3
  • What have you tried? The javascript `for`-loop syntax is [readily available](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript) with even a cursory web search, so what have you tried? – dcsohl Jun 25 '15 at 02:10

1 Answers1

0

Notice that the only thing that is changing is the text in document.getElementById("..."). So you can use an array with the three text items: ["etnik","Jantina","warganegara"]. And loop through them:

var array = ["etnik","Jantina","warganegara"];

for(var i = 0; i < array.length; i++)
{
    var a = document.getElementById(array[i]);
    var strUser = a.options[a.selectedIndex].value;
    var strUser1 = a.options[a.selectedIndex].text;
    if (strUser == 0) {
        alert("Sila isikan ruangan yang kosong.");
    }
}
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54