3

I have a form with same name but different ids.I am able to serializearray , but unable to get current id.

<form action="test.php" id="loginform" name="loginform" method="post">
     <input name="title[]" id="title1" type="text" value="" tabindex="1" />
     <input name="title[]" id="title2" type="text" value="" tabindex="2" />
     <input  name="title[]" id="title3" type="text" value="" tabindex="3" />
     <input type="submit" name="submit" value="Submit" id="submit" tabindex="4" />
 </form>

$('#loginform').bind('submit', function() { 
    var elements = $(this).serializeArray();
    $.each(elements, function(i, element) {
        var temp = $('#' + element['name']);
       var name = this.name; alert(name);
 var id = $(this).attr("id");alert(id); 
        (temp.val() == '') ? temp.css({'background': '#FFC4C4', 'border': '1px solid #F00'}) : temp.removeClass('hightlight');
    });
    return false;
});

I am getting the name but not id.Can anyone look into this....

Demo

Ullas Prabhakar
  • 416
  • 2
  • 10
  • 24

2 Answers2

2

I think I understand your question, but I'm not 100% certain. If my understanding is correct, you are trying to iterate through your inputs and get the ID attribute of each.

If that's all you need to do, there is a much simpler way of achieving it.

$('#loginform').submit(function(ev) {
    $('input[type=text]', this).each(function(index, element) {
      alert($(element).attr('id'));
    });
    ev.preventDefault();
});

So, a quick breakdown:

  • Firstly, $('input[type=text]', this) gets all text inputs from the form we are submitting.
  • Then, we iterate through them using .each().
  • For each element, we use .attr() to get the ID, and pass it to alert() to display to the user.

Updated Demo

Jim O'Brien
  • 2,512
  • 18
  • 29
0

.serializeArray() will return only name and value of each object. So iterating over the collection will not get you the value.

.serializeArray()

Encode a set of form elements as an array of names and values.

rahul
  • 184,426
  • 49
  • 232
  • 263
  • I know .serializeArray() will return only name and value pair, but this refers to the current element.So from there can we retrieve id ? – Ullas Prabhakar Jan 27 '11 at 11:47