Newbph Newbph - 17 days ago 5
Ajax Question

How to validate each textbox using javascript ajax?

I wanted to validate each dynamic textbox such that when an input (pid) is entered in each textbox the input will be passed into an ajax and return true if personName is in the DB and if the personName from DB is the same with the personName in another textbox. But I'm unsure of how to do it. Here is my sample checking.

Javascript:

function validateTextbox() {


var pName = document.getElementsByClassName("personNameStatic");
var pNameVal = pName[0].value;//value of personName in another textbox

var pn = document.getElementsByClassName("personName"); //person name which will be passed to an ajax to get personName from DB

for (var i = 0; i < pn.length; i++) {
var pnval = pn[i].value;


$.ajax({
//ajax here
success: function(data) {

var personName = data.pName;

if (pNameVal == personName){ //compare pNameVal (from another textbox) to personName (coming from DB)

alert("Name is valid.");
}else{

alert ("Name is invalid");
}
},//END: success
});//END: ajax
}

}


HTML:

<td><input type="text" name="personName" id="personId-1" class="personName" size="30"/></td> //textbox which inputs the pid
<td><input type="text" name="personName" id="personId-2" class="personName" size="30"/></td> //textbox which inputs the pid
<td><input type="text" name="personName" id="personId-3" class="personName" size="30"/></td> //textbox which inputs the pid


<td><input type='text' id='personIdstatic' class='personNameStatic' size='30' value='John' disabled /></td>


Please help on how to validate each textbox? Thanks

Answer

You can iterate a loop throughout every text box and can check & validate textbox's values to you db values

var personName = data.pName; // this is from back-end 

    $(".personName").each(function(){
      if($(this).val() == personName ){

       }else{

       }
    })
Comments