简体   繁体   中英

how can i check all form element isn't empty on one function?

<form action="surl.php" method="get" id="surl">
   <input type="text" placeholder="name of column" name="column_name"/>

   <textarea placeholder="description for column name" name="description"></textarea>


   <div class="surl"><input type="url" placeholder="first url" name="url1"/></div>


   <div class="surl"><input type="url" placeholder="second url" name="url2"/></div>


   <div class="surl"><input type="url" placeholder="third url" name="url3"/></div>



   <input type="submit" class="surl_submit">
</form>

if one of my input fields or textarea is empty while submit button click, i don't want to post the form.how can i control this form's input and textarea fields at the same time instead of controling one by one?

Add a class to the input/textarea tags, call a function on submit and do something like this:

document.querySelector('.surl_submit').onclick = function(e) {

    var input = document.getElementsByClassName('classname');

    var i = input.length;

    while(i--) {

        if(input[i].value == '') {

            // you could display some sort of message here

            e.preventDefault();
            return;
        }
    }
};

Call the validation function on click of submit and submit form only when if the all requirements are fullfilled.

DEMO

HTML

<form action="surl.php" method="get" id="surl">
   <input  id="mytext1" type="text" placeholder="name of column" name="column_name" value="" />
   <textarea  id="mytext2" placeholder="description for column name" name="description"></textarea>
   <div class="surl"><input class="inputUrl" type="url" placeholder="first url" name="url1" value=""/></div>
   <div class="surl"><input  class="inputUrl" type="url" placeholder="second url" name="url2" value=""/></div>
   <div class="surl"><input class="inputUrl" type="url" placeholder="third url" name="url3"/ value=""></div>
   <input type="submit" class="surl_submit" onclick="return validateForm()" value="submit">
</form>

SCRIPT

function validateForm(){
    var input1 = document.getElementById('mytext1');
    var textarea1 = document.getElementById('mytext2');
    var allInputs = document.getElementsByClassName('inputUrl');
    for(var i=0; i<allInputs.length; i++){
        if(!allInputs[i].value){
            return false;
        }
    }

    if(!input1.value){
        return false;
    }else if(!textarea1.value){
        return false;
    }
}

you can add a class for all relevant fields somthing like: "tovalidate" and using jquery:

if ($('.tovalidate').filter(function(){return $(this).val()=='';}).length>0)
    //do not submit
else
    //submit

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