Duplicate Form Fields - javascript

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>

Related

Entering multiple records on same HTML page

I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>

Appending a new field with unique id

I have code which takes a name and a number. I want to have a button that, when you click it, adds another field for another name and number, but it should have a different id because I need to use it for later.
So far, I have the code below but it doesn't work.
function addField() {
var id = 2
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend>
<code>New Phone Number</code>
</legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner" />
<br />
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br />
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
Just define id outside the function like this, otherwise it will initialize with value 2 on every call of addField().
var id = 2
function addField() {
var name = 'Name of Owner # ' + id
var phonenum = 'Phone number'
$('.form-group').append('<br><label for="' + id + '">' + name + ':</label><input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner' + id + '" />')
$('.form-group').append('<br><label for="' + id + '">' + phonenum + ':</label><input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber' + id + '"/>')
id++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-sm-4">
<fieldset>
<legend><code>New Phone Number</code></legend>
<label for="NewPnOwner">Name of Owner #1: </label>
<input type="text" class="form-control" name="NewPnOwner" id="NewPnOwner">
<br>
<label for="Phonenumber">Phone number: </label>
<input type="number" class="form-control" name="NewPnNumber" id="NewPnNumber" />
<br>
<input type="button" id="button" value="Add New Field" onclick="addField()" />
</fieldset>
</div>
But
even though that this is the correct solution to your problem, I would not recommend you to give them ids like that. I can't think of any valid reason to solve any problem like so. There are probably better solutions for your real problem.

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');">

Multiple text fields in single div with jQuery dynamic form

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');
});

Categories

Resources