1

I am trying to ask the user to input at least 1 of the options. From my codes the user need to input all the inputs. Can anyone please check what is wrong with my code?

jsp

<form role="form" method="POST" id="search" action="Servlet" 
      onsubmit="return validateForm();">

    <label>Name</label> 
    <input name="name">

    <label>ID</label> 
    <input name="id">

    <label>no</label> 
    <input name="no">

    <button type="submit">Search</button>
</form>

javascript

function validateForm() {
    var name = document.forms["search"]["name"].value;
    var id = document.forms["search"]["id"].value;
    var no = document.forms["search"]["no"].value;

    if ( (name == null || name == "") || (id == null || id == "") || (no == null && no == "")) {
        alert("Please enter either one to perform search");
        return false;
    }
}
5
  • Please post your HTML also Commented Jan 20, 2014 at 13:58
  • Look your condition: if name is empty OR if id is empty OR no... so if one of those fields is empty it won't continue Commented Jan 20, 2014 at 14:20
  • @Sergio I put the html codes. Please take a look. Thanks! Commented Jan 20, 2014 at 14:27
  • You have a typo on the onsubmit, there is an h too much. Also, if you don't use strict comparison you can just use if (!name && !id && !no) {...} except if 0 is valid though Commented Jan 20, 2014 at 14:27
  • Textbox values can not be null so that is a waste of a check. Commented Jan 20, 2014 at 14:30

2 Answers 2

1

Just a little logic adjustment should do the trick:

if ( 
    (name != null || name != "") || 
    (id != null || id != "") || 
    (no != null && no != "") 
) {

This is saying that if any one of the fields has a value, continue.

Sign up to request clarification or add additional context in comments.

2 Comments

why you do the parenthesis thing?! you shouldn't group since you're ORing all the cases ;)
I didn't. The OP did. I just reversed the logic.
0
function validateForm() {
    var name = document.forms["search"]["name"].value;
    var id = document.forms["search"]["id"].value;
    var no = document.forms["search"]["no"].value;

    if ( (name == null || name == "") && (id == null || id == "") && (no == null || no == "")) {
        alert("Please enter either one to perform search");
        return false;
    }
}

or you would do it as @isherwood did. also take care of typos like not closing your input tag should goes like this <input name="no"/> good luck and I hope this would help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.