Atiq
Atiq

Reputation: 166

pass variable value in hidden text field in jquery

Hey guys I want to pass variable pid value to hidden text field pid but unable to do so.

HTML code:

<div id="overlay_forma">
<h4>Another popup</h4>

<input id="addElement" type="button" value="Add to Form" />
<input id="removeElement" type="button" value="Remove" />
<form id="samplecode" name="samplecode" method="POST" action="<%= request.getContextPath() %>/AddProjectTaskDAO">
 <fieldset>
  <legend><b>&nbsp;&nbsp;&nbsp;Dynamically added form elements&nbsp;&nbsp;&nbsp;</b></legend>
  <div id="generatedForm">
   <div>
    <input id="processForm" type="submit" value="Submit to Process" />
   </div>  
  </div>
 </fieldset>
 </form>
 <center><a href="#" id="closea" >Close</a></center>
 </div>

jQuery code:

var counter = 1;

$("#addElement").click(function(event){

 var pid=$('#addElement').data('pid');
 var pname=$('#addElement').data('pname');

 if(counter>10){
     alert("Only 10 textboxes allow");
     return false;
}   

 var $newDiv = $(document.createElement('div'))

  .attr("id", 'TextBoxDiv' + counter);

 var $newInput = $("<label>Input Box: </label>" + "<input type='hidden' id='pid' name='pid' value='pid'>" + "<select name='uname'><c:forEach items='${ual}' var='u'><option value='<c:out value='${u.uname}'></c:out>'><c:out value='${u.uname}'></c:out></option></c:forEach></select>" + "<textarea rows='5' cols='15'></textarea>" + "<input type='text'>");
 $newInput
   .attr("name", "$('#addElement').data('pid')" + counter)
   .addClass("text")
   .attr("name", "uname" + counter)
   .addClass("text")
   .attr("name", "ptdesc_emp" + counter)
   .addClass("text")
   .attr("name", "ptestd_time_alloc" + counter)
   .addClass("text");
 $newInput.appendTo($newDiv);
 $newDiv.appendTo($("#generatedForm"));

 counter++;

 });

I have also tried adding $('#addElement').data('pid') instead of pid in val of hidden text field but still unable to show the output of pid.

Any help is appreciated.

Upvotes: 2

Views: 1297

Answers (1)

Shaunak D
Shaunak D

Reputation: 20626

Use '"+pid+"' - pid is variable.

<input type='hidden' id='pid' name='pid' value='"+pid+"'>

and not

<input type='hidden' id='pid' name='pid' value='pid'>

Replace with this line

var $newInput = $("<label>Input Box: </label>" + "<input type='hidden' id='pid' name='pid' value='"+pid+"'>" + "<select name='uname'><c:forEach items='${ual}' var='u'><option value='<c:out value='${u.uname}'></c:out>'><c:out value='${u.uname}'></c:out></option></c:forEach></select>" + "<textarea rows='5' cols='15'></textarea>" + "<input type='text'>");

Note :

In the code you are trying to append id='pid' stays there for every append event. This will result into duplicate IDs.

Working Fiddle.

Upvotes: 1

Related Questions