Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onclick function stops HTML5 required from working

Good day,

I am working on a form where all my text fields have a required attribute; I noticed that when i clicked on submit required attribute does not show a pop up to validate if a field is empty.

I have two submit buttons on my page both using an onclick submitform function; One opens up a new tab and the other submits the form and goes to a new page.

For debugging purposes i remove the button that opens up a new tab and remove the onclick attribute on my second button and it work; I have been googling all day but i cannot seem to find the same scenario i have at the moment.

I believe it has to do with my JS but i am not sure what to add or remove on my code; Please see my code below.

JavaScript

 function submitForm(action,newtab)
 {
    document.getElementById('add2').target = newtab ? '_blank' : '_self';
    document.getElementById('add2').action = action;
    document.getElementById('add2').submit();
 }

HTML

 <form id="add2" action="add5.php" method="post">
 <input placeholder="First Name" tabindex="1"
 name="fname" maxlength="128" size="30" required>
 <input placeholder="Last Name" tabindex="12"
 name="lname" maxlength="128" size="30" required>
 <button tabindex="3" value="Save"
 name="save" onclick="submitForm('add3.php',1);" 
 type="submit">Child Information</button>
 <button tabindex="4" value="Save"
 name="save" onclick="submitForm('add5.php',0);" 
 type="submit">Save Details</button>
 </form>

I have a button attribute but i have set it to type="submit" and i am pretty much sure that works as i have already tested it when i removed the onclick functions; My question is can i required attribute worked without removing the onclick function of JavaScript?

Any help is much appreciated.

like image 434
Emc_tgn15 Avatar asked Feb 11 '15 16:02

Emc_tgn15


Video Answer


2 Answers

I found the answer to my question, The problem is that i was binding onClick method to the submit. The onClick will trigger first which results in it getting past the validator.

Solution is i change the onClick to onSubmit on my HTML code.

<button tabindex="3" value="Save"
name="save" onsubmit="submitForm('add3.php',1);" 
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onsubmit="submitForm('add5.php',0);" 
type="submit">Save Details</button>
like image 119
Emc_tgn15 Avatar answered Oct 18 '22 03:10

Emc_tgn15


You just need to use the "checkValidity()" method on the form before submitting in your onclick function like this:

if($("#add2").checkValidity()) { 
 document.getElementById('add2').submit();
}

See this fiddle: http://jsfiddle.net/36uv2e52/33/

like image 45
Heath Avatar answered Oct 18 '22 02:10

Heath