简体   繁体   中英

Form field validation using switch case inside for loop in javascript

In my HTML, I have created a form with two attributes - item name and item price and a button whose onclick() event is going to call a javascript function temp() . Below is the javascript code I have attached:

function temp(){


var a = 2
var b = 4;
var f = [a,b];
for(var i = 0; i <= f.length-1;i++)
{
    switch(f[i])
    {
        case f[0]:
            if (f[0] == 2) {
             alert("hell");
              }
            break;
        case f[1]:
            if (f[1] == 4) {
                alert("hello");
            }
            break;
    }
}

this correctly displays two alert messages - "hell" and "hello" respectively when I just click a button. Problem is with below code:

function temp() {
var a = document.form1.item_name.value;
var b = document.form1.price.value;
var f = [a,b];
for(var i = 0; i <= f.length-1;i++)
{
    switch(f[i])
    {
        case f[0]:
            if (f[0] == "") {
             alert("hell");
              }
            break;
        case f[1]:
            if (f[1] == "") {
                alert("hello");
            }
            break;
    }
}


} 

this code alerts "hell" twice but how?

The reason is that your first switch case of f[0] is always going to be satisfied and alert 'hell'

this works as anticipated:
    switch(i)
    {
        case 0:
            if (f[0] == "") {
             alert("hell");
              }
            break;
        case 1:
            if (f[1] == "") {
                alert("hello");
            }
            break;
    }
}

Your switch case is working as follows:-

switch("")
{
case ""
Alert hell
break
case ""
Alert hello
break
}

So your first case is satisfied everytime. Also don't mix up switch and if together, use either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM