简体   繁体   中英

Correct way to validate input of a select element

What is the correct way to validate if an option is selected on a dropdown? I have some select elements (fieldset) which are set to display none and others that are visible. I want to validate only the ones that are visible, otherwise the form won't submit.

For Example:

<fieldset id="a1_1">
  <select name="a1_1">
     <option value="" selected="selected">Select Age</option>
     <option value="1">1</option>
     <option value="2">2</option>
  </select>
</fieldset>

<fieldset id="a1_2" style=" display: none;">
  <select name="a1_2">
     <option value="" selected="selected">Select Age</option>
     <option value="1">1</option>
     <option value="2">2</option>
  </select>
</fieldset>

<fieldset id="a2_1">
  <select name="a2_1">
     <option value="" selected="selected">Select Age</option>
     <option value="1">1</option>
     <option value="2">2</option>
  </select>
</fieldset>

<fieldset id="a2_2" style=" display: none;">
  <select name="a2_2">
     <option value="" selected="selected">Select Age</option>
     <option value="1">1</option>
     <option value="2">2</option>
  </select>
</fieldset>

I was trying something like this without any luck:

var x = document.forms["x"]["a1_1"].value;
    if (x == null || x == "")
    {
        alert("Age must be selected");
        return false;
    }

In your case I would change to this:

x = $('select[name="a1_1"]').val();//get the value in jquery

if(x!=1 || x!= 2 || !x)

Useful link

Using jquery your could try something like below :

if ($("select[name=a1_1]").val().length <= 0)
{
    alert("Age must be selected");
    return false;
}

and use same for others, this will fix your issue.

I would do something like this:

<fieldset id="a1_1">
  <select name="a1_1" errorMessage="Age must be selected">
     <option value="0" selected="selected">Select Age</option>
     <option value="1">1</option>
     <option value="2">2</option>
  </select>
</fieldset>

//Catch submit form event
$('form').submit(function(){
    //Go through all select elements of the form
    $(this).find('select').each(function(){
        //Validate the selected value
        if($(this).val() === "0")
        {
            //Display the defined error message if needed
            var msg = $(this).attr('errorMessage');
            alert(msg);
            //And return false to invalidate the form submission
            return false;
        }
    });
});

它不起作用,因为您有两个id / name为a1_1 ,请尝试给字段集赋予不同的id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM