Irfan Ahmed
Irfan Ahmed

Reputation: 9364

Validate multiple fields with same name jquery?

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;">    

Upvotes: 0

Views: 794

Answers (3)

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

Try this:

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

Upvotes: 0

musefan
musefan

Reputation: 48415

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

Upvotes: 3

gdoron
gdoron

Reputation: 150253

$('form').submit(function(){
    var unSelected = $('select').filter(function(){
        return this.value === "";
    }).length > 0;

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

Upvotes: 1

Related Questions