3

HTML:

<fieldset id="10">
  <h1>Select a color:</h1>
  <select name="color">
    <option>red</option>
    <option>blue</option>
  </select>
</fieldset>

JS:

var fields = $(":input").serializeArray();

$.each(fields, function (i, field) {
  var field_id = $(field.name).closest("fieldset").attr('id');
  $("#results").append('<a href="'+field_id+'">'+field.value+'</a>');
});

All I get is undefined?

When I do: field.name, it gives me "color". I want to be able to find the parent or closest fieldset that this form element belongs to.

I expect field_id to equal "10" in this example.

MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

1 Answers1

3

I do: field.name, it gives me "color"

Use

var field_id = $('[name=' + field.name+']').closest("fieldset").attr('id');
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 1
    Yes this works. Thank you. (I will accept) Sort of a side question but can you point to tutorial/post (like a quickstart) on JS debugging (perhaps recommend tools?) because I find it a royal pain in the arse to debug JS. (e.g. I'll do a console.log() and I get [Object object] and firebug console is just a drop down after down and I have no idea what I'm looking at or where to start.) Appreciate the advice. Thanks again. – MrPizzaFace Feb 20 '14 at 19:17
  • @feed_me_code, A good start [How can I debug my JavaScript code?](http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code), [Debugging JavaScript](https://developers.google.com/chrome-developer-tools/docs/javascript-debugging) and http://www.qtweb.net/pages/ibr9600.html – Satpal Feb 20 '14 at 19:22
  • Thanks for the tips. Glad to know it's not just me. :) – MrPizzaFace Feb 20 '14 at 19:32