Can we get an identifier from several elements with the same name using a serialized array

I have a form with the same name but with different identifiers. I can serializearray but cannot get the 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 get a name but not id.Can, does anyone look into this ....

Demo

+3
source share
2 answers

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

If this is all you need to do, there is a much simpler way to achieve it.

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

So quick crash:

  • Firstly, it $('input[type=text]', this)receives all text inputs from the form we submit.
  • .each().
  • element .attr() alert() .

+2

.serializeArray() . .

.serializeArray()

.

0

Source: https://habr.com/ru/post/1788163/


All Articles