[dancer-users] Getting param name of dynamically named <input> tag

Dave Cross dave at dave.org.uk
Sat Oct 10 09:35:02 BST 2015

On 09/10/15 22:02, Richard Reina wrote:
> I have a input tag in a form:
> <div class="col-xs-4 col-md-4">
> 	  <div id="p_scents">
> 	    <p>
>                <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="email address" /></label>
> 	    </p>
> 	  </div>
> 	</div>
> Which gets it's name from the JS function below. However, that name I can't figure out. I have tried
> p_scnt_1 but it comes back undefined. Any ideas what the param name would be for each sequentially added item?
> Here's a working example of the form:http://jsfiddle.net/jaredwilli/tzpg4/4/
> $(function() {
>          var scntDiv = $('#p_scents');
>          var i = $('#p_scents p').size() + 1;
>          $('#addScnt').live('click', function() {
>                  $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
>                  i++;
>                  return false;
>          });
>          $('#remScnt').live('click', function() {
>                  if( i > 2 ) {
>                          $(this).parents('p').remove();
>                          i--;
>                  }
>                  return false;
>          });
> });

This code generates multiple input elements with the same id (p_scnt) - 
this is invalid HTML. There should only ever be one instance of any 
given id on any page. I suggest that you generate the id using similar 
logic to that which you use to generate the name.

Here's what I did to investigate what the names of your generated 
elements are:

* Opened http://jsfiddle.net/jaredwilli/tzpg4/4/ in Firefox
* Clicked 'Add another input Box' a couple of time.
* Selected all of the output frame from 'Add' to the last 'Remove'
* Right-clicked and selected 'View Selection Source'

I then got a new window containing the generated HTML. The important 
parts look like this (when lightly cleaned up:

<label for="p_scnts"><input id="p_scnt" size="20" name="p_scnt"
     value="" placeholder="Input Value" type="text"></label>
<label for="p_scnts"><input id="p_scnt" size="20" name="p_scnt_2"
     value="" placeholder="Input Value" type="text"></label>
<a href="#" id="remScnt">Remove</a>
<label for="p_scnts"><input id="p_scnt" size="20" name="p_scnt_3"
     value="" placeholder="Input Value" type="text"></label>
<a href="#" id="remScnt">Remove</a>

So you can see that the first input element has a name of "p_scnt", the 
second one has a name of "p_scnt_2" and the third one is "p_scnt_3".

Which is why you couldn't find one called "p_scnt_1". You never create 
one with that name.

Hope that helps,


Dave Cross :: dave at dave.org.uk

More information about the dancer-users mailing list