0

I am struggling with a javascript/jquery issue. I have multiple forms that are created within a foreach loop and multiple javascript functions that are created in a foreach loop.

Essentially, the first form looks like this:

<form role="form" action="/save/parishioner" id="1" name="1" method="post">
<input type="text"  class="form-control" name="acct_number" id="acct_number" value="test" onchange="save1()" />
<input type="text"  class="form-control" name="first_name" id="first_name" value="name" onchange="save1()"/>
</form>

The second form looks like this:

<form role="form" action="/save/parishioner" id="2" name="2" method="post">
<input type="text"  class="form-control" name="acct_number" id="acct_number" value="test" onchange="save2()" />
<input type="text"  class="form-control" name="first_name" id="first_name" value="name" onchange="save2()"/>
</form>

And the functions looks like this:

alert($('form[name="2"]').serialize());
alert($('form[name="3"]').serialize());

When I try to serialize the data and alert it, the first alert returns blank and the second alert shows the second form serialized.

Why is it not finding the first form?

I would greatly appreciate any help!

Andy
  • 698
  • 12
  • 22
  • Is this the example that gives the outcome you described? Because you don't have a form with `name=3` so the first alert should work, and the second shouldn't – Lixus May 25 '17 at 21:40
  • the question should say alert 1 and alert 2 and not 2 and 3. – user1687763 May 25 '17 at 21:44
  • Do you think it would work if I added a letter before the number in the id? – user1687763 May 25 '17 at 21:46
  • It works just as you have it https://jsfiddle.net/f9pp06a3/ I changed the names to 1 and 2 – Lixus May 25 '17 at 21:46
  • Hard to say without seeing more of the JS, but it might also, check this out https://css-tricks.com/ids-cannot-start-with-a-number/ Before I said classes and IDS but I was wrong, apparently it's just IDs, but I never do it with either, just for consistency – garek007 May 25 '17 at 21:47
  • Sorry my comment was more geared toward CSS so probably not a factor in your code https://stackoverflow.com/questions/22141358/why-can-an-element-id-not-start-with-an-integer – garek007 May 25 '17 at 22:02

1 Answers1

1

From the code you have posted (unless this is a mistake in your post) you are actually getting a serialized alert from the first call not the second. Your selectors in the alert are wrong

alert($('form[name="2"]').serialize());
alert($('form[name="3"]').serialize());

so the values you are placing in name param of the form and then in the selector in your alert do not match. They should be:

alert($('form[name="1"]').serialize());
alert($('form[name="2"]').serialize());