Pedro Pedro - 6 months ago 12
jQuery Question

validation in form not working

I don't know what im doing wrong, i have a form and using this function to check if the input is empty...what Iam trying to do is to highlight the field by adding a class to the text field...but if i add this line


name.addClass("empty");


to the function, the function dont work

function register()
{
if(document.myForma.userid.value == '')
{
name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required")
name.addClass("empty");
return false;
}
}

Answer

Declare your name variable as local, or use a different name for it, - global window.name already exists and is not changeable.

console.log(name);

function register() {
  if (document.myForma.userid.value == '') {
    var name = $("#userid");
    document.myForma.userid.focus();
    $("#empty").html("This field is required");
    name.addClass("empty");
    return false;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="myForma" name="myForma" onsubmit="return register();">
  <input id="userid" type="text" />
  <div id="empty"></div>
  <input type="submit" />
</form>