0

I have multiple select inputs in my page that are dynamically created with same name.

My code:

<select name="area[]" id="area[]" class="area">
    <option value="">Select Area</option>
    <?  
     $cities = $this->city_model->get_all($posters->product_id);
         foreach($cities as $city) { ?>
           <option value="<?=$city->city_id?>"><?=$city->city_name?></option>
        <? } ?>
 </select>

I want that user select a value from each select input, I am using jQuery function like this:

 $('.area').each(function(){ 
if($(this).val() == "") {
  alert("please select Area");
}  return false;
});

$('.quantity').each(function(){ 
if($(this).val() == "" || $(this).val() == 0) {
  alert("please select Quantity");
  return false;
}
});
$('#form').submit();

i did same same with it, it is also working, but it also submits the form as well, even i restrict it at

 <input type="submit" name="something" id="something" value="something" onclick="checkType();return false;">    
2
  • 1
    What is "not working"? Commented Apr 26, 2013 at 14:46
  • Any errors in the JavaScript console? Commented Apr 26, 2013 at 14:47

3 Answers 3

3

You are missing a close brace on your if statement. Try this:

$('.area').each(function(){ 
   if($(this).val() === "") {
      alert("please select Area");
      return false;
   }
});

EDIT: I re-added the return false part, as it is likely the OP only wants to show 1 alert regardless of how many items are invalid.

Here is a working example

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

1 Comment

== "" is true for 0, might be problematic.
1
$('form').submit(function(){
    var unSelected = $('select').filter(function(){
        return this.value === "";
    }).length > 0;

    if (unSelected)
        alert('Error!');
});

2 Comments

Or var unSelected = $('select').filter(function(){ return !this.value; }).length; ?
@Johan, !0 evaluates to true, which isn't suitable here.
0

Try this:

<script>$('.area').each(function() {
        if ($(this).val() == '') {
            alert("please select Area");
            return false;
        }
    });   
</script>

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.