0

I have the following form

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

I am able to get the element name but not its id using this code.

$('#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.id; alert(id); ///even id = this.attr("id"); not getting

        var value = this.value; 
        (temp.val() == '') ? temp.css({'background': '#FFC4C4', 'border': '1px solid #F00'}) : temp.removeClass('hightlight');
    });
    return false;
});

Demo

Ullas Prabhakar
  • 416
  • 2
  • 10
  • 24

1 Answers1

1

Updating the answer on this for you:

This code:

var id = $(this).id;alert(id);

Should become this:

var id = $('input[name="' + name + '"]').attr("id");
alert(id);

See the code working here: http://jsfiddle.net/Ct8zf/5/

Please note that accoring to .serializeArray() documentation that the only elements which are serialized are the names and values.

Hope this helps.

Mitch Malone
  • 882
  • 6
  • 17
  • Tried all possibilities but it says undefined var id = this.id;alert(id);,var id = this.attr("id");alert(id); – Ullas Prabhakar Jan 27 '11 at 09:42
  • Thanks Mitch for your effort and time taken ,but var id = $(this).attr("id"); is also not working. – Ullas Prabhakar Jan 27 '11 at 09:50
  • Maybe try creating a jsFiddle with with an alert, I'd be happy to take a look! :-) – Mitch Malone Jan 27 '11 at 09:53
  • Okay, so here is the ultra hacky way to do it... I would consider why you're actually serializing the array and how else you might achieve it... :-) alert($('input[name="' + name + '"]').attr("id")); jsFiddle: http://jsfiddle.net/Ct8zf/5/ – Mitch Malone Jan 27 '11 at 13:49