0

Below, I am trying to iterate through each attribute in an input element. It isn't working and I'm not sure why. Is this an incorrect use of the object named input? How do I change this?

<script>
   $('form.trade').submit(function(e) {
      e.preventDefault();
      input=$(this).find(':input:first');
      value='';

      $.each(input.attributes, function(i, attrib){
        if (attrib.name!='type'){
            value +=attrib.name + ":" + attrib.value + ";";
        }
      });
      });
</script>
<form class="trade" id="24243">
<input type="hidden" available="4" pid="24243" cardname="something" yay="blah">
Available: <p class="available">4</p>
<input type="submit" value="add card">
</form>
<br/>
<form class="trade" id="24245">
<input type="hidden" available="7" pid="24243" cardname="somethik" yay="blakk">
Available: <p class="available">7</p>
<input type="submit" value="add card">
</form>
alrightgame
  • 341
  • 2
  • 7
  • 20

3 Answers3

1

It's "attributes" on the input array that doesn't make sense.

$.each(input.attributes

The result of $(this).find(':input') returns a jQuery selection (array) of items.

Are you trying to iterate through the inputs attributes? $.each(input[i].attributes is what you're looking to do, where i is an iterator through the input collection.

~ Here's what you want to do:

<script>
      $('form.trade').submit(function(e) {
           e.preventDefault();
           var $inputs=$(this).find(':input:first');
           var value='';
           $inputs.each(function(i,input){
             $.each(input.attributes, function(j,attrib){
                 if (attrib.name!=='type'){
                value +=attrib.name + ":" + attrib.value + ";";
                 }   
             });
           });
           console.log(value); // what do you want to do with value??
      });
</script>
Nirvana Tikku
  • 4,105
  • 1
  • 20
  • 28
0

I guess I have to go through the input first. I'm not sure why, but it solved it easily enough.

        value='';
        input.each(function(){
        $.each(this.attributes, function(i, attrib){
            if (attrib.name!='type'){
                value +=attrib.name + ":" + attrib.value + ";";
            }
        });
        });
alrightgame
  • 341
  • 2
  • 7
  • 20
0

You could have used plain javasript:

var elem = document.getElementById('testElement');
for (var i = 0; i < elem.attributes.length; i++) {
    var att = elem.attributes[i];
    if (att.specified == true) {
    console.log(att.name + " " + att.value);
    }
}

How to iterate through all attributes in an HTML element?

Community
  • 1
  • 1
Dave
  • 3,812
  • 5
  • 31
  • 39