dikei
dikei

Reputation: 439

How can I validate the same field under three different forms on the same html page

Hi I am trying to make this validation work, it actually works if I use it once on the page, but would like to use it more than once on the same page and somewhow it doesn't work

Some help will be much appreciated my js below:

function validateMe(){          
        var a = $('input[name="c"]');
        var b = $('input[name="d"]');

        if( a != null && a.length == 1 &&
            b != null && b.length == 1 ){

            var url = "/apply.do?code=" + encodeURIComponent( a[0].value ) +
                "&city=" + encodeURIComponent( b[0].value );

            if (typeof XMLHttpRequest != "undefined") {
                req = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }       
            req.open("GET", url, true);         
            req.onreadystatechange = callback;
            req.send();
        }
    }   
    function callback(){
        if (req.readyState == 4) {
            if (req.status == 200) {
            $(document).ready(function() {
                $('input').addClass('error');
                    $(".error-red").css('display','block').text(req.responseText);
            });
            }
        }
}

And HTML, which I am using under three different forms

<div>
    <label>code</label>
    <input type="text" name="c" class="code"/>  
    <a href="javascript:validateMe()">apply</a>
    <label class="error-red" for="code"></label>
    <input type="hidden" name="city" value="gara">  
    <div class="clear"></div>           
</div>

Thanks

Upvotes: 0

Views: 62

Answers (1)

cypherabe
cypherabe

Reputation: 2603

it is a question of how you want to target the fields.

At the moment, your validateMe() function selects all inputs with the name 'c' and all with the name 'd', that are available in the DOM. But It only does anything "real" when there is exactly one element of each.

So, what could you do? If you want to validate all forms at once, you could loop over all selected fields

quick and dirty:

var a = $('input[name="c"]');
var b = $('input[name="d"]');    

if( a != null && a.length >= 1 &&
        b != null && b.length == a.length ){
    for (i = 0; i < a.length; i++) {

        // your code, just use a[i], b[i] instead of a[0]..
    }
}

If you want to target exactly one form it is easier to use ids. One way to do it is to use a fixed prefix for each form, for example form1_.

HTML
 <input type="text" id="form1_code" name="code"....
 <a href="javascript:validateMe('form1')">apply</a>
 ....

 JS
 function validateMe(formPrefix) {
     var a = $('#' + formPrefix + '_code');
     ...
     if (a != null...) {
         // use a directly, it is not an array in this case, so no need for a[0] etc

Upvotes: 1

Related Questions