-1

I know there is another question about this here but this just isn't working for me.

So I have a very very large form with about 40 fields and its a pain to go trough each field individually, so I divided the 50 fields into categories and asigned an id to each input categories, so for example, there are 10 prices fields for 10 quantities on 4 categories: Standard shipping, express shipping, rush shipping, super rush shipping. so I named all of the prices under one category with the same id, say for example standard shipping is

<id input type="text" name="s_qty_25" id="s_cf" />
<id input type="text" name="s_qty_50" id="s_cf" />
<id input type="text" name="s_qty_100" id="s_cf" />
.... and so on

my form is defined like this:

<form method="post" id="creation_form" action="actions/add_prices.php">
  ....
</form>

and the jQuery I use to validate is like this:

$(function() {
$('#creation_form').submit(function(e){

    $("#cs_f").each(function(index, obj){
        var cs_f_val = $(obj).val();
        if(cs_f_val == ''){
            $(obj).attr('style', 'background:red;');
            valid = false;
        }
    });

    //...repeat the snipet for each 3 remaining price groups

    return valid;
});
});

basically turn the fields red if empty and cancel submition. however only the first field will get its red background!

Thanks for the help folks :)

Community
  • 1
  • 1
RicardoE
  • 1,665
  • 6
  • 24
  • 42
  • 1
    You can't do that. Multiple elements with the same `id` are not allowed. Use a class instead. The reason you only get one result from `each` is that jQuery assumes an `id` selector will only match one element and doesn't look for more. – verdesmarald Oct 11 '12 at 05:12

2 Answers2

3

There should only be one field with a particular id. That's why it's called an id!

Try using a class instead:

<id input type="text" name="s_qty_25" class="s_cf" />
<id input type="text" name="s_qty_50" class="s_cf" />
<id input type="text" name="s_qty_100" class="s_cf" />

then

$(".cs_f").each
craigmj
  • 4,827
  • 2
  • 18
  • 22
2

first things.. id should always be unique ... so use class instead

<id input type="text" name="s_qty_100" class="s_cf" />

and in your javascript , try this

$(function() {
$('#creation_form').submit(function(e){

    $(".cs_f").each(function(index, obj){
    var cs_f_val = $(obj).val();
    if(cs_f_val == ''){
        $(obj).attr('style', 'background:red;');
        valid = false;
    }
  });

  //...repeat the snipet for each 3 remaining price groups

  return valid;
 });
});
bipen
  • 36,319
  • 9
  • 49
  • 62