Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit with javascript and input required

I was trying to submit things using a div, HTML5, JavaScript. If I use a submit button the validator (required attribute in the inputs) works the button doesn't submit info. But if I use a div tag it doesn't validate and send the info. Any way to fix it? Or should I do the whole code to validate the info and stop the submit?

<form action="index.php" method="get" name='myform'>
  <ul>
    <li class="row">
      <label class="labels" for="username">Username</label>
      <input type="text" id="txtUser" required>
    </li>
    <li class="row">
      <label class="labels" for="password">Password</label>
      <input type="password" id="txtPass" required>
    </li>
    <li id="row2">
      <div class="button"><a href="javascript: submitform()">Submit</a></div>
      <input type="submit">
    </li>
  </ul>
</form>

http://www.dropmocks.com/mCyfGJ

Im using the following code. Javascript submit: http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml

HTML

enter code here

like image 997
nanoalvarez Avatar asked Oct 01 '22 21:10

nanoalvarez


1 Answers

If you are submitting via JS then you need to call the form validation yourself. I don't see any issues in your post that would prevent the submit though (without validation). But here's a working example. Keep in mind that not all browsers support html5 validation.

function submitform() {
  // Get first form element
  var $form = $('form')[0];

  // Check if valid using HTML5 checkValidity() builtin function
  if ($form.checkValidity()) {
    console.log('valid');
    $form.submit();
  } 
  
  else {
    console.log('not valid');
  }
  
  return false
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="index.php" method="get" name='myform'>
  <ul>
    <li class="row">
      <label class="labels" for="username">Username</label>
      <input type="text" id="txtUser" name="sds" required>
    </li>
    <li class="row">
      <label class="labels" for="password">Password</label>
      <input type="password" id="txtPass" required>
    </li>
    <li id="row2">
      <div class="button"><a href="" onclick="return submitform()">Submit</a></div>
      <input type="submit">
    </li>
  </ul>
</form>
like image 149
cyberwombat Avatar answered Oct 05 '22 11:10

cyberwombat