开发者

javascript getElementById() for loop (empty textbox validation)

开发者 https://www.devze.com 2023-02-10 06:06 出处:网络
i have the following code that validate against empty textboxes. If there are empty ones, the form will not be able to submit successfully.

i have the following code that validate against empty textboxes. If there are empty ones, the form will not be able to submit successfully.

However,I cannot seem to get the alert to popup after clicking sub开发者_StackOverflow中文版mit looping through the elements to find if there are any empty boxes to fill in.

any advice/correction on the looping?


Move your onSubmit into the tag instead of the Submit button, for one... it's not firing the event at the proper time. It should be like:

<form action="whatever" onSubmit="return submitform();">

Also change the last line of the function,

else document.forms[0].submit();

to

return true;

This should solve the problem of it not running properly, and not intercepting the submission of the form.

Also, you shouldn't have multiple items with the same ID. It's not valid HTML and can cause problems with some browsers *cough*IE*cough*, though you'd probably get away with it in this case.


You may want to read the jsfiddle documentation.

Here you'll find a working version of your code. The (corrected) function:

function submitform() {
    var msg = ''
        ,elems = document.getElementById('tasks').getElementsByTagName('input');
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].id && elems[i].id.match(/^t/i) && 
            elems[i].value.replace(/^\s+|\s+$/,'') === '')
        {
            msg += elems[i].id+ ' is empty!\n';
        }
    }
    if (msg.length > 0) {
        alert("one or more of the inputs is/are empty\n"+msg);
        return false
    }
    else alert('we are cool');
    return true;
}

A bit more worked out: http://jsfiddle.net/GbX8m/4/


  1. You are not following dom rules. ID should be uniquer for each element. You should have unique id. Read xhtml guidelines.

  2. document.getElementById will return one element not array. If you want to apply on group use function which apply on group like document.getElementsByClassName.

  3. form tab should have action . if you want it to on same page use. action="#"

  4. Fire submit form on form submit not button click and submitform should return true of false depending on if form is valid or not.

  5. If that is for education purpose then good. Otherwise use framework like jquery those have many function which will reduce your work.

0

精彩评论

暂无评论...
验证码 换一张
取 消