0

I have the form

<form action="test.php" id="loginform" name="loginform" method="post">

         <input name="title[]" id="title1" type="text" value=""  />
         <input name="title[]" id="title2" type="text" value=""  />
         <input  name="title[]" id="title3" type="text" value=""  />
         <input  name="label" id="label" type="text" value=""  />
         <input type="submit" name="submit" value="Submit" id="submit"/>  
</form>

I am trying to get id of each element like this

$('#loginform').bind('submit', function () {
    {
        var value = {};
        var x = 0;
        var y = 0;
        var temp = {};
        var elements = $(this).serializeArray();
        $.each(elements, function (i, element) {
            var tempname = elements[i].name;
            var tempvalue = elements[i].value;
            if (tempname.indexOf("[]") === -1) {
                var tempid = $("#" + tempname);
            } else if ($.inArray(String(tempname.replace("[]", "")), temp) == -1) {
                temp[y] = String(tempname.replace("[]", ""));
                var tempid = $("#" + tempname.replace("[]", x));
                y++;
            } else if ($.inArray(String(tempname.replace("[]", "")), temp) == 0) {
                x++;
                var tempid = $("#" + tempname.replace("[]", x));

            } else {
                var tempid = $("#" + tempname.replace("[]", x));
            }(tempvalue == "") ? tempid.addClass("hightlight").css({
                'background': '#FFC4C4',
                'border': '1px solid #F00'
            }) : tempid.removeClass("hightlight");
        });
        return false;
    });

This inArray always return -1 irrespective of string in the array.

can any one look into this.Tried a lot but all in vain

hakre
  • 193,403
  • 52
  • 435
  • 836
Ullas Prabhakar
  • 416
  • 2
  • 10
  • 24

3 Answers3

1

Update:

Check out the demo

Code Used:

var elements = $('#loginform').serializeArray();

for (var p = 0; p <= elements.length; p++){
  if (elements[p]) {
   var counter = 1;
   counter += p;
   var id = elements[p].name.replace(/\[\]/, '');
   id = (id.indexOf('title') !== -1) ? id + counter : id;
   alert(id);
 }
}

You can simply get the id of each element inside the form like this:

$('#loginform :input').each(function(){
  var id = this.id;
  // manipulate id variable
});
Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

First I would suggest taking look at jquery.validator to do the form validations: jQuery Validation. It makes form validation easier.

From the code posted I think you are trying to validate the form element values and you are trying to validate the fields against non blank values.

For that you can try something like this:

$('#loginform').bind('submit', function (){
    var elements = $(this).serializeArray();
    $(":input").each(function{
      var $this = $(this);
      ($this.val()=="") ? $this.addClass("hightlight").css({
                'background': '#FFC4C4',
                'border': '1px solid #F00'
        }) : $this.removeClass("hightlight");

    });
 });

Now since you have named the title textboxes as title[], I presume you want to validate those textboxes to have atleast one value. If that's the case, use this(this can be used where there are more than one group of elements):

$('#loginform').bind('submit', function (){
    var elements = $(this).serializeArray();
    //Trim all Inputs
    $(':input', this).each(function(){
        $(this).val($.trim($(this).val()));
    });
    //Validated non Grouped Inputs
    $(':input:not([name*="\[\]"])', this).each(function{ //Selects all input elements that don't end with []
        var $this = $(this);
        ($this.val()=="") ? $this.addClass("hightlight").css({
                            'background': '#FFC4C4',
                            'border': '1px solid #F00'
            }) : $this.removeClass("hightlight");
    });
 //Validated Grouped Inputs
  $(':input[name$="\[\]"]', this).each(function(){
        var $namedEls = $(':input[name="' + this.name + '"]', this);
            //If no element in the name group is selected then mark as invalid.
        if($namedEls.filter('[value!=""]').length == 0){
            var $this = $namedEls.eq(0);
            $this.addClass("hightlight").css({
                'background': '#FFC4C4',
                'border': '1px solid #F00'
            }) : $this.removeClass("hightlight");
        }
    });
});
Chandu
  • 81,493
  • 19
  • 133
  • 134
-1

This is an old post, but I thought I'd add my thoughts. Copying the source code from the link below, you will be able to add any element attribute you would like to the returned array. This way your implementation is exactly that of jQuery. Yea, you will need to manually update your code if the jQuery source is updated, but that is the same with the other solutions posed.

https://searchcode.com/codesearch/view/25323764/

var
  rbracket = /\[\]$/,
  rCRLF = /\r?\n/g,
  rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
  rsubmittable = /^(?:input|select|textarea|keygen)/i,
  rcheckableType = /^(?:checkbox|radio)$/i;

$.fn.extend({
  customSerializeArray: function() {
    return this.map(function() {

      // Can add propHook for 'elements' to filter or add form elements
      var elements = $.prop(this, 'elements');
      return elements ? $.makeArray(elements) : this;
    })
    .filter(function() {
      var type = this.type;

      // Use .is(':disabled') so that fieldset[disabled] works
      return this.name && !$(this).is(':disabled') &&
        rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
        (this.checked || !rcheckableType.test(type));
    })
    .map(function(i, elem) {
      var val = $(this).val();

      if (val == null) {
        return null;
      }

      if ($.isArray(val)) {
        return $.map(val, function(val) {
          return { name: elem.name, value: val.replace(rCRLF, '\r\n') };
        });
      }

      return { name: elem.name, value: val.replace(rCRLF, '\r\n') };
    }).get();
  }
});