I want to verify in JavaScript that my required fields are not blank

前端 未结 3 1870
遥遥无期
遥遥无期 2021-01-25 02:03

Hopefully this is basic JavaScript and the answer is easy since I am new at this. I just want to make sure all required fields are not blank before the user can proceed. In my <

3条回答
  •  旧巷少年郎
    2021-01-25 02:32

    If I were you, I'd give each one of those elements a common name or a class.

    For example:

    
    
    
    

    Since you are tying all those elements as a group by class.

    Then your javascript would be a lot easier:

    var flagInvalid = false;
    var tempArray = document.getElementsByClassName("not_blank");
    for (var i = 0; i < tempArray.length; i++)
    {
        if (tempArray[i].value == "" || tempArray[i].value === undefined || tempArray[i].value == null){
            flagInvalid = true;
            break; 
        }
    }
    
    if (flagInvalid == false){
        xmlhttp.open('POST', 'payment.php', true);
        xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xmlhttp.send(cn1&ag2&hm3&bg4&fn5&ln6&email$ad8&ad9&ct10&st11&zp12); 
    
    } else { alert ("Please enter all required fields."); }
    

    Btw, I strongly advise not to use "alert". Try to create a messaging system on the document itself. Like:

    
    

    Your css would look like this:

    .hidden { display: none; }
    .show { display: inline; }
    

    Your javascript would be changed to:

    if (flagInvalid == false){
        var log = document.getElementById("log");
        log.className = 'hidden';
        xmlhttp.open('POST', 'payment.php', true);
        xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xmlhttp.send(cn1&ag2&hm3&bg4&fn5&ln6&email$ad8&ad9&ct10&st11&zp12); 
    
    } else { 
        var log = document.getElementById("log");
        log.className = 'show';
    }
    

提交回复
热议问题