-1

I am writing three functions in javascript to do different things. Search functions only needs firstname and lastname. Add and update functions needs everything to filled out completely. I have those working, however when submitting form, if anything is missing, it alerts me but still submits it. I don't want it to do that, how can i do it?

function search() {
        checkme = false
        //alert('all feilds must be filled out');
        var nameExpression = /^[a-zA-Z]+$/;
        firstName = document.getElementById('firstName').value;
        lastName = document.getElementById('lastName').value;

         //check firstname
        if (firstName!=""&&nameExpression.test(firstName)) {

            checkme = true;
        }else{
            document.getElementById("firstName").classList.add("is-invalid");
            alert("Please enter valid first name");
        }
        //check lastName
        if (lastName!=""&&nameExpression.test(lastName)) {

            checkme = true;
        }else{
            document.getElementById("lastName").classList.add("is-invalid");
            alert("Please enter valid last name");
        }
        return checkme;
        }

, here is how i am calling the function as well

<input  name="Action" type="submit" name="Search" value="Search" onclick="return search();"">

2 Answers2

1

The reason your function fails to stop submission, is because of a system called event bubbling, where an event propagates up the DOM tree, and any handlers related to that event are triggered. There are also default events that occur on certain actions. Some of these are cancelable events, one of which is the Form Submit event. The e.preventDefault() command basically cancels the default action of the event, which is submitting the form, and prevents it from submitting regardless of the output of your function. We then call the submit() function manually when all requirements are satisfied.

Here's a version that I feel is shorter and easier to understand. No checkme variables needed either. It assumes your form has the id yourForm, and submits it if both first and last names pass the RegEx check.

function search(e) {
  e.preventDefault();

  const nameExpression = /^[a-zA-Z]+$/;
  const firstName = document.getElementById('firstName').value;
  const lastName = document.getElementById('lastName').value;
  const yourForm = document.getElementById('yourForm');

  if (nameExpression.test(firstName) && nameExpression.test(lastName)) {
    yourForm.submit();
  } else {
    alert('All fields must be filled out, and contain only alphabets');
  }
}

document.getElementById('yourForm').addEventListener('submit', search);
<form id="yourForm">
  <input type="text" id="firstName" placeholder="First Name" />
  <br>
  <input type="text" id="lastName" placeholder="Last Name" />
  <br>
  <input name="Action" type="submit" name="Search" value="Search">
</form>

P.S. You can do what you are trying to do here in pure HTML by adding the pattern attribute to your first and last name inputs. This also helps in case the user has an extension like NoScript installed, but the downside is you cannot control how the validation error looks.

tripathiakshit
  • 624
  • 5
  • 17
  • That _is_ a nicer version for the function — but you don't answer the question of _why_ "it alerts me but still submits it." Yes, you do the necessary thing with `e.preventDefault()` but you don't mention what the OP's issue is or that this is how to cure that problem. Stackoverflow is not a code-writing service or a discussion forum, it is a Q&A site — good answers should help people learn and help _future_ readers, not just the original poster's immediate problem. – Stephen P Jul 22 '20 at 17:00
  • @StephenP Thanks for your feedback. I've added an explanation. Take a look and please edit it if necessary. – tripathiakshit Jul 22 '20 at 17:15
  • Thank you for the explanation. I am doing what you describe and it is still submitting and searching database. Only difference now is that it is not alerting me if field is empty. I am guessing it is not running the function properly. – alienarun Jul 22 '20 at 20:51
  • Hello @alienarun, I have added a sample form and added the search function as the onsubmit listener to it. The issue you were having was probably because `e` wasn't getting properly assigned the value of the `Form` object. This way of adding the listener fixes it. – tripathiakshit Jul 27 '20 at 16:06
0

(I'm beginner/intermediate in JS) I once also worked on something like this. I would suggest to add a paramater of 'e' in your function, en then writing "e.preventDefault" In your code. It would prevent the default submit action of your form. And then, you can submit the form in JS if it matches a certain condition, and if not, it will give you an alert. Im guessing checkme, firstName and lastName weren't defined yet.

function search(e) {
        e.preventDefault();
        var checkme = false;
        //alert('all fields must be filled out');
        var nameExpression = /^[a-zA-Z]+$/;
        var firstName = document.getElementById('firstName').value;
        var lastName = document.getElementById('lastName').value;

         //check firstname
        if (firstName!=""&&nameExpression.test(firstName)) {
            checkme = true;
        } else {
            document.getElementById("firstName").classList.add("is-invalid");
            alert("Please enter valid first name");
        }

        //check lastName
        if (lastName!=""&&nameExpression.test(lastName)) {
            checkme = true;
        } else {
            document.getElementById("lastName").classList.add("is-invalid");
            alert("Please enter valid last name");
        }

        if (checkme == true) {
          your_form.submit();
        }

This may not be a perfect solution to your problem, but this is roughly how I do these things with JS and validating forms. I hope this helped.

Edit:

The code is the author's source code, I tried to not edit it too much.

Artii4
  • 3
  • 2
  • I'd like to point out that you probably don't need the empty string check in your if statements, since the test will fail if the string is empty. Also, this will pass even if only one of the names passes because you're setting the checkme to `true` in both statements, but not setting it to false in the else block, or returning the code, so it will keep executing and eventually submit. You're right about preventing the default action though! – tripathiakshit Jul 22 '20 at 16:42