Multiple text fields in single div with jQuery dynamic form - javascript

Using the jQuery code from here, but I am trying to have multiple text inputs in each div. It displays correctly and increments and saves the name and id for the first element, but for the second age input, it only stores the first input.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled','');
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#btnAdd').attr('disabled','');
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
</head>
<body>
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Name: <input type="text" name="name1" id="name1" />
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
</form>
</body>
</html>
Here is what my new form and jQuery code looks like.
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
Name: <input type="text" name="name1" id="name1" />
Age: <input type="text" name="age1" id="age1" />
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
newElem.children(':first')
.attr('id', 'age' + newNum)
.attr('name', 'age' + newNum);

Your script only updates the first input, you need to loop through and update all inputs in the cloned div
$('#btnAdd').click(function () {
var num = $('.clonedInput').length;
var newNum = num + 1;
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.find(':input').each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, newNum));
$(this).attr('name', $(this).attr('name').replace(/\d+/, newNum));
});
$('#input' + num).after(newElem);
$('#btnDel').attr('disabled', '');
if (newNum == 5) $('#btnAdd').attr('disabled', 'disabled');
});

Related

Pass the values from View to Controller for Dynamically populated forms

I have a form in which the TextBox is dynamically populated. The user has the flexibility to add and remove TextBox which is done using JQuery.
I would need to pass the value of TextBox to my Controller on Submit.
This is my View.
#using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" }))
{
<h4>Add new Q&A</h4>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br />
</div>
</div>
<input type="button" name="Add" id="Add" value="Add" class="btn btn-success" />
<input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br />
<textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br />
#Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { #class = "form-control", required = "required" })
<br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br />
<input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br />
<input type="submit" name="Submit" id="Submit" class="btn btn-success" />
}
This is how my JS looks
$(document).ready(function () {
var counter = 2;
$("#Add").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter +
'"> <br />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#Remove").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
Sorry if I sound lame. Just getting started with MVC!
You can create a simple model having property Questions of List<string> type and other required properties.
Then from jQuery you can add multiple TextBoxes using a simple logic:
<input type="text" name="Model.Questions[" + index + "]" id="Model_Questions_" + index />
Render using:
#for (int i = 0; i < Model.Questions.Count; i++)
{
#Html.TextBoxFor(x => Model.Questions[i], { .... })
}
When you post your form, all values in questions textboxes will be posted to your model's Questions list.
Note: I have not written above code in VS, so there may be some errors which you can fix yourself.

Dynamic add multi fields in javascript

I am beginner in javascript. I need to dynamic add multifields in existing form that have same id.
first fields has this name :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
And when clicking "Add another text input" I want a new fields with
<input type="text" name="myInputs[1][address]">
<input type="text" name="myInputs[1][whitelist]">
and clicking again on "Add another text input"
<input type="text" name="myInputs[2][address]">
<input type="text" name="myInputs[2][whitelist]">
When submit post only the first fields are posted :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
Here the code :
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs["+ (counter + 1) +"][address]'><input type='text' name='myInputs["+ (counter + 1) +"][whitelist]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<div id="dynamicInput">
Entry 1<br>
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">

Duplicate Form Fields

I have some code that I'm using to allow the user to add products. They can control the number of products added, as well as delete products they've created. My problem is that with the code I'm using, I've only managed to be able to change the id of the second div as well as the name/id of the first input. How can I change the names of all the inputs, not just the first input?
The javascript:
<script type="text/javascript">
$(document).ready(function() {
$('#add').click(function() {
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
$('#input' + num).after(newElem);
$('#remove').attr('disabled','');
});
$('#remove').click(function() {
var num = $('.clonedInput').length;
$('#input' + num).remove();
$('#add').attr('disabled','');
if (num-1 == 1)
$('#remove').attr('disabled','disabled');
});
$('#remove').attr('disabled','disabled');
});
</script>
The form:
<form id="myForm">
<div id="input1" class="clonedInput">
<p>Product Name: <input type="text" name="name1" id="name1" /></p>
<p>Product Description:</p>
<textarea rows="10" cols="50" name="desc1" id="desc1"></textarea>
<p>Brand Name: <input type="text" name="brand1" id="brand1" /></p>
<p>Product Code Number: <input type="text" name="code1" id="code1" /></p>
<p>West Texas Co-op Bid Product Number (if different from the Product Code Number): <input type="text" name="coop1" id="coop1" /></p>
<p>Commodity processing availability:</p>
<p><input type="checkbox" name="yes" id="yes1" value="Yes"> Yes <input type="checkbox" name="no" id="no1" value="No"> No</p>
<p>If yes, what is the commodity processing code number?: <input type="text" name="comm1" id="comm1" /></p>
</div>
<div>
<input type="button" id="add" value="Add Product" />
<input type="button" id="remove" value="Remove Product" />
</div>
</form>
Live example: http://test.joshrodg.com/wp-content/themes/rodgersconsulting/test.php
I figured it out...I was able to tweak what I found here: http://jsfiddle.net/e6cwd/9/
The JQuery:
<script src="http://code.jquery.com/jquery-1.4.2.js" type="text/javascript"></script>
The JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = new Number(num + 1);
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":first").children(":first").attr("id", "name" + newNum).attr("name", "name" + newNum);
newSection.children(":nth-child(3)").children(":first").attr("id", "desc" + newNum).attr("name", "desc" + newNum);
newSection.children(":nth-child(4)").children(":first").attr("id", "brand" + newNum).attr("name", "brand" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "code" + newNum).attr("name", "code" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "coop" + newNum).attr("name", "coop" + newNum);
newSection.children(":nth-child(7)").children(":first").attr("id", "yes" + newNum).attr("name", "yes" + newNum);
newSection.children(":nth-child(7)").children(":nth-child(2)").attr("id", "no" + newNum).attr("name", "no" + newNum);
newSection.children(":nth-child(8)").children(":first").attr("id", "comm" + newNum).attr("name", "comm" + newNum);
$(".clonedSection").last().append(newSection)
$("#btnDel").attr("disabled","");
if (newNum == 5)
$("#btnAdd").attr("disabled","disabled");
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length; // how many "duplicatable" input fields we currently have
$("#clonedSection" + num).remove(); // remove the last element
// enable the "add" button
$("#btnAdd").attr("disabled","");
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$("#btnDel").attr("disabled","disabled");
});
$("#btnDel").attr("disabled","disabled");
});
</script>
The HTML:
<form id="myForm">
<div id="clonedSection1" class="clonedSection">
<p>Name: <input type="text" name="name" id="name" /></p>
<p>Product Description:</p>
<p><textarea rows="10" cols="50" name="desc" id="desc"></textarea></p>
<p>Brand Name: <input type="text" name="brand" id="brand" /></p>
<p>Product Code Number: <input type="text" name="code" id="code" /></p>
<p>West Texas Co-op Bid Product Number (if different from the Product Code Number): <input type="text" name="coop" id="coop" /></p>
<p>Commodity processing availability: <input type="checkbox" name="yes" id="yes" value="Yes"> Yes <input type="checkbox" name="no" id="no" value="No"> No</p>
<p>Commodity processing code number (if applicable): <input type="text" name="comm" id="comm" /></p>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
</form>

How to generate HTML with jquery clone with different names?

I have HTML like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
</div>
<input type='button' id='add' value='Add'>
jQuery:
$("input#add").live( 'click', function(){
$("#main").append("<br />");
$("#child-0").clone(false).appendTo( $("#main") );
});
Above code is working but it is creating elements with same name. I want to generate it something like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
<div id='child-1'>
<input type='text' name='data[1][name]'>
<input type='text' name='data[1][dob]'>
<input type='text' name='data[1][location]'>
</div>
</div>
What is the simple solution.
Thanks
$("input#add").live( 'click', function(){
$("#main").append("<br />");
var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
cloned.find('[name^=data]').attr('name', function() {
var index = this.name.match(/\[(\d)\]/);
if (index != null && index.length > 1) {
var newIndex = parseInt(index[1], 10) + 1;
return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']');
}
return this.name;
});
});​

Problem with jQuery clone(): clone input without value

I am using jquery .clone() and it is working fine. However my problem is that when I clone my input field it also clones the value of the previous field. I don't want to clone the value. How can I overcome this issue?
Here is my code
function addrow(){
var num = $('.clonedInput').length;
var newNum = new Number(num + 1);
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
$('#input' + num).after(newElem);
jQuery('.clonedInput').each(function(){
jQuery('#total', jQuery(this)).unbind('blur');
});
var ci = jQuery('.clonedInput:last');
jQuery('#total', ci).blur(function() {
addrow();
});
}
Regards,
Faizan
try this:
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum).val('');
I might be late with this, but it's not clear whether your "#input" is actually an input field. Only then you can set it's value.
After you place your cloned element, try:
newElem.find('input:first').val(null);
add this line after the clone
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
newElem.removeAttr('value');
or
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum).removeAttr('value');
Works fine with me:
<div id="con">
<input id="input1" value="some text" />
</div>
$("#input1").clone().val("").attr("id", "input2").appendTo("#con");
http://jsfiddle.net/sXL2b/
or by using insertAfter:
http://jsfiddle.net/sXL2b/1/
Try this instead of cloning:
http://jsfiddle.net/sXL2b/4/
Do you really need to clone?
You can clean all the inputs with .val(""):
<div class="">
<div id="references">
<div class="">
<div class="">
<div class="">
<input type="text" name="name-reference" class="" placeholder="Name" >
</div>
<div class="">
<input type="text" name="relationship-reference" class="" placeholder="Relationship" >
</div>
</div>
</div>
<div class="">
<div class="">
<div class="">
<input type="text" name="employer-reference" class="" placeholder="Employer" >
</div>
<div class="">
<input type="tel" name="phone-reference" class="" placeholder="Phone Number" >
</div>
</div>
</div>
<div class="">
<button id="add" class="">Add</button>
<button id="remove" style="display:none;">Remove</button>
</div>
</div>
The script:
var reference_form_index = 0;
$("#add").on('click', function(){
reference_form_index ++;
$(this).parent().parent().after($("#references").clone().attr("id","references" + reference_form_index));
$("#references" + reference_form_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + reference_form_index);
$(this).attr("id",$(this).attr("id") + reference_form_index);
$(this).val('');
});
$("#remove" + reference_form_index).css('display', 'inline');
$(document).on( 'click', "#remove" + reference_form_index, function(event){
$(this).parent('div').parent('div').remove();
} );
$("#add" + reference_form_index).remove();
});
You can see it in action on:
http://jsfiddle.net/pnovales/yF2zE/5/

Categories

Resources