www.webdeveloper.com
Results 1 to 4 of 4

Thread: Javascript dynamic field validation

  1. #1
    Join Date
    Jul 2008
    Posts
    3

    Javascript dynamic field validation

    I've a page which renders a group of input fields x times depending on the user's choice of x from a dropdown (1-6).
    I want to validate their input (mandatory fields) so I do this using Javascript with a function IsEmpty to which I pass the field name and text to display in an alert.
    I can't concatenate a string with the field name (e.g. lastname_ + '01') as I receive an error that object doesn't exist.
    Can someone please explain how I can perform validation on the dynamic fields?

    Thanks in advance,

    Alan

  2. #2
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428

  3. #3
    Join Date
    Jul 2008
    Posts
    3

    Code so far

    Please see a static version of the code below which works, simplified to show one input field called txtFirstName.

    My dynamic page containing the form 'frmStep1' will contain 1-6 instances, i.e. txtFirstName_0 - txtFirstName_5 depending on user input from a previous page
    so I want to be able to create a loop in the Javascript to check the input accordingly, I'm guessing I therefore need to pass in the number as a parameter to checkInput.
    I tried lots of combinations to get this working and kept hitting errors stating that the object didn't exist.

    <form ... name="frmStep1" onSubmit="return checkInput();">
    </form>

    function isEmpty(formElement, message) {
    formElement.value = trim(formElement.value);

    _isEmpty = false;
    if (formElement.value == '') {
    _isEmpty = true;
    alert(message);
    formElement.focus();
    }

    return _isEmpty;
    }

    function checkInput()
    {
    with (window.document.frmStep1) {
    if (isEmpty(txtFirstName, 'Enter first name')) {
    return false;
    } else {
    return true;
    }
    }
    }

  4. #4
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Code:
    <form name="frmStep1" onsubmit="return checkInput(this);">
    Code:
    <script type="text/javascript">
    function isEmpty(formElement, message){
    formElement.value = trim(formElement.value);
    var _isEmpty = false;
    if (formElement.value == ''){
    _isEmpty = true;
    alert(message);
    formElement.focus();
    }
    return _isEmpty;
    }
    function checkInput(f){
    var i=0, t;
    while(t=f['txtFirstName_'+[i++]]){
    if(isEmpty(t,'Please fill all the required fields!')){return false}
    }
    }
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles