Cloning empty form fields - javascript

I am still attempting to create blank fields that users can add on the fly. I am attempting to clone the following hidden template but I can't get it to add.
My HTML
<div class="_100">
<fieldset id="FieldBlank">
<div id="readroot" class="hidden">
<div class="_100">
<div class="_50"> QA Sample ID:<input type="text" id="QASampleID" name="QASampleID"></div>
<div class="_50" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<div class="_100">
<div class="_40">
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select></div>
<div class="_30">
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select></div>
<div class="_30">
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select></div>
</div>
</div>
</fieldset>
</div>
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<hr /><div id="writeroot"> </div>
My javascript
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
I just cannot get it to work! Is it because this script is not jquery? It doesn't seem to be because it is hidden because when I unhide it the button still doesn't work to add the clones? I am so pulling my hair out right now. I need you help!

Have you tried something like:
$("#readroot input").clone().appendTo("body"); // Or wherever you want to append them to
And, yeah, don't hide stuff manually. Use jQuery's toggle function instead:
$("#readroot").toggle(); // Or hide()

Related

How to use different attribute on change the second select option

I'm trying to change the value of my input box by changing two different select options.
The first select box is product_type with two different data attributes on the options: data-price and data-price_c.
The second Select box pay_type is to selecting between data-price or data-price_c, to update the value of lprice.
This is what I've tried:
var sp = document.getElementById('select_product');
var lp = document.getElementById('lprice');
var count = document.getElementById('count');
var fp = document.getElementById('price');
var pt = document.getElementById('paytype');
var selected_type = pt.options[pt.selectedIndex];
sp.onchange = function(){
var selected = sp.options[sp.selectedIndex];
if (selected_type === 1){
lp.value = selected.getAttribute('data-price');
} else {
lp.value = selected.getAttribute('data-price_c');
}
fp.value = "";
};
sp.onchange();
count.onchange = function(){
fp.value = lp.value * count.value;
}
<div>
<label for="select_product">Select Product</label>
<select name="product_id" id="select_product" onchange="update();">
<option value="1" data-price="10000" data-price_c="11000">Product 1</option>
<option value="2" data-price="20000" data-price_c="21000">Product 2</option>
<option value="3" data-price="30000" data-price_c="31000">Product 3</option>
</select>
</div>
<div>
<label for="paytype">Pay type:</label>
<select name="paytype" id="paytype">
<option value="1">Cash</option>
<option value="2">Dept</option>
</select>
</div>
<div>
<label for="lprice">Single Price:</label>
<input type="text" name="lprice" id="lprice" class="form-control" tabindex="1" readonly/>
</div>
<div>
<label for="count">Count:</label>
<input type="number" name="count" id="count" class="form-control" tabindex="1" />
</div>
<div>
<label for="price">Full Price:</label>
<input type="text" name="price" id="price" class="form-control" tabindex="1" readonly/>
</div>
I hope I understated you correctly what needs to be done from code and explanation:
Your first problem was that you had your selected_type outside of you onchange function so it wasn't getting the changed options onchange.
Second is that you where trying to compare values 1 & 2 with element without actually extracting those values from element (missing .value on selected_type)
I assumed you will need to update the values on your Pay type change too as well as Select Product, so there is nit trick to wrap both HTML selects into one div in this case div id="wrapper" and that will listen on both selects and call function if any of them are changed. So now you call it on wrapper.onchange.
I would also advise to put your calculation fp.value = lp.value * count.value; inside this function to update total price on change of any of those elements so I wrapped your Count: into wrapper div.
Hope this helps.
var sp = document.getElementById('select_product');
var lp = document.getElementById('lprice');
var count = document.getElementById('count');
var fp = document.getElementById('price');
var pt = document.getElementById('paytype');
var wrapper=document.getElementById('wrapper');
wrapper.onchange = function(){
var selected = sp.options[sp.selectedIndex];
var selected_type = pt.options[pt.selectedIndex].value;
if (selected_type === "1"){
lp.value = selected.getAttribute('data-price');
}
if (selected_type === "2"){
lp.value = selected.getAttribute('data-price_c');
}
fp.value = "";
fp.value = lp.value * count.value;
};
wrapper.onchange();
<div id="wrapper">
<div>
<label for="select_product">Select Product</label>
<select name="product_id" id="select_product" >
<option value="1" data-price="10000" data-price_c="11000">Product 1</option>
<option value="2" data-price="20000" data-price_c="21000">Product 2</option>
<option value="3" data-price="30000" data-price_c="31000">Product 3</option>
</select>
</div>
<div>
<label for="paytype">Pay type:</label>
<select name="paytype" id="paytype">
<option value="1">Cash</option>
<option value="2">Dept</option>
</select>
</div>
<div>
<label for="lprice">Single Price:</label>
<input type="text" name="lprice" id="lprice" class="form-control" tabindex="1" readonly/>
</div>
<div>
<label for="count">Count:</label>
<input type="number" name="count" id="count" class="form-control" tabindex="1" />
</div>
</div>
<div>
<label for="price">Full Price:</label>
<input type="text" name="price" id="price" class="form-control" tabindex="1" readonly/>
</div>

Dynamically accesing a button and creating a list Javascript

Alright, so I am stuck. So the break down of the project is when you enter your age, and select an option from the drop down list when you click add, a list is created and that input is plugged into the list. I have to also show that list somewhere on the page. I hope I explained that correctly.
Anyways, I've been trying everything from trying to create a new div, to creating an unordered list programmatically, and trying to display it within the body under the last div, but my code below doesn't execute when I hit the add button. By the way I CAN NOT edit the HTML in anyway and I CAN NOT use JQuery. I have to use pure Javascript. Any tips or help would be great!
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add.onlick = 'addToList()';
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There was some syntactical errors in the code, especially the button click event handler. Here is the correct code.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
var add = document.getElementsByClassName('add');
add[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function addToList() {
var li = document.createElement("li");
//li.setAttribute('id', age.value + dropDown.value);
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<h1>Household List</h1>
<div class="builder">
<ol class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
There are numerous issues in your code
All the for attributes and input attributes can be defined the html instead of using js
button type default is submit ,so add button type="button" in <button class="add">add</button>
add.onlick = 'addToList()'; is wrong ;the function is not a string , replace it with document.getElementsByClassName('add')[0].onclick = addToList;
var age = document.getElementsByName("age")[0];
var dropDown = document.getElementsByName("rel")[0];
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
document.getElementsByClassName('add')[0].onclick = addToList;
function addToList() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(age.value + ' ' + dropDown.value));
ul.appendChild(li);
return false;
}
<body>
<h1>Household List</h1>
<div class="builder">
<o class="household"></o>
<form method="POST" action="form-handler">
<div>
<label>Age
<input type="number" name="age" min="0" max="120">
</label>
</div>
<div>
<label>Relationship
<select name="rel" required>
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add" type="button">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
</body>
There is a problem with your HTML you have an o tag instead of an order list tag. This may fix the code. Also when you click on the add button the form is posted so I would remove the post until the end.

Manipulate value of child node attribute in a cloned div?

I am cloning the following div in my jsp:
<div id="row" class="">
<div class="form-group">
<div class="control-label">
<label for="name"><b> Select Name: </b></label>
</div>
<div class="control-label">
<select class="form-control" name="names" id="names">
<option value="" disabled="disabled" label="Select a name"></option>
<option value="1">Bradley</option>
<option value="2">Anderson</option>
<option value="3">Sonya</option>
</select>
</div>
<div class="control-label">
<label for="ranks"><b> Rank : </b></label>
<input type="text" value="1" name="rank" id="rank" readonly="">
</div>
</div>
</div>
I am executing the cloning in javascript:
var i = 0;
function duplicate() {
var original = document.getElementById('row');
var clone = original.cloneNode(true);
clone.id = "row" + ++i;
if(!document.getElementById('row3')){
original.parentNode.insertBefore(clone, document.getElementById('nextDiv')); //nextDiv not shown in jsp for simplification
}
}
How do I access the value of "rank" so that every time the div is cloned, the value increments by 1?
Basically I want something like clone.getElementById('rank') though I know that's not right syntax. I tried clone.setAttribute('rank', i++) but the setAttribute only accesses the attributes of the div and not the child node in the div. Is there a simpler way to do this?
Try using Array.prototype.forEach() , for loop, Element.children to increment id, for, value properties of cloned element .control-label elements child nodes . Note, for attributes at label elements should correspond to id of select , input elements; added "s" at for="names" , for="ranks" label elements
var i = 0;
function duplicate() {
var original = document.getElementById('row');
var clone = original.cloneNode(true);
clone.id = "row" + ++i;
Array.prototype.forEach.call(clone.querySelectorAll(".control-label")
, function(el, index) {
for (var j = 0; j < el.children.length; j++) {
// increment `id`
if (el.children[j].id !== "") {
el.children[j].id = el.children[j].id + i;
}
// increment `for` attribute
if (el.children[j].htmlFor !== "") {
el.children[j].htmlFor = el.children[j].htmlFor + i;
}
// increment `#ranks`-n `value`
if (el.children[j].name === "ranks") {
el.children[j].value = 1 + Number(el.children[j].value)
}
}
})
if (!document.getElementById('row3')) {
original.parentNode.insertBefore(clone,
// nextDiv not shown in jsp for simplification
document.getElementById('nextDiv'));
}
}
duplicate()
<div id="row" class="">
<div class="form-group">
<div class="control-label">
<label for="names"><b> Select Name: </b>
</label>
</div>
<div class="control-label">
<select class="form-control" name="names" id="names">
<option value="" disabled="disabled" label="Select a name"></option>
<option value="1">Bradley</option>
<option value="2">Anderson</option>
<option value="3">Sonya</option>
</select>
</div>
<div class="control-label">
<label for="ranks"><b> Rank : </b>
</label>
<input type="text" value="1" name="ranks" id="ranks" readonly="">
</div>
</div>
</div>
<div id="nextDiv"></div>

How to increment the input field names in the middle of them

http://www.quirksmode.org/dom/domform.html
I am trying to implement this extend form function in my project. Since I am compiling with CakePHP naming convention, in my extend form I have 2 field names:
[Student][0][age]
[Student][0][grade]
The script doesn't work because it is appending the counter only at the end of a field name all alike like this: fieldName + counter, whereas I am trying to increment, as you might have guessed it, like this:
[Student][1][age]
[Student][1][grade]
[Student][2][age]
[Student][2][grade]
I am new to Javascript and hopefully someone can advise how to work this out.
HTML:
<span id="readroot" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<br /><br />
<div class="row">
<div class="col-lg-3">
<div class="form-group required"><label for="Student1Age">Age</label><input name="data[Student][0][age]" class="form-control" placeholder="Age" maxlength="11" type="text" id="Student1Age" required="required"/></div>
</div>
<div class="col-lg-3">
<div class="form-group required">
<label for="Student1Grade">級別</label>
<select name="data[Student][0][grade]" class="form-control" id="Student1Grade" required="required">
<option value="">Please Select</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
</select>
</div>
</div>
</div></span>
<span id="writeroot"></span><input class="btn btn-default" type="button" onclick="moreFields()" value="Give me more fields!" />
Javascript:
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
You have to replace this one line like follows.
Yours:
newField[i].name = theName + counter;
New one:
newField[i].name = "[Student][" + counter + "][" + theName + "]";
I made a working sample page out of your script. Check the following link.
http://sugunan.net/demo/extend_form.php

cloning template Jquery

I have a rather long complicated form to be used to record field data. One section of the form requires the ability to add a "Field Blank" section with no data recorded AND the ability to add a duplicate section where everything (including the data from the field blank section) is duplicated. The only different thing that would change on the duplicate would be the SampleID
The field blank script
<script>
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
</script>
The duplicate script
<script>
$(document).ready(function(){
var template_index=0;
$("#add_FieldDup").click(function(){
template_index++;
$(this).parent().before($("#template").clone().attr("id","template" + template_index));
$("#template" + template_index).css("display","inline");
$("#template" + template_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + template_index);
$(this).attr("id",$(this).attr("id") + template_index);
});
$("#remove_Dup" + template_index).click(function(){
$(this).closest("fieldset").remove();
});
});
});
</script>
My form
<h3>Water Samples</h3>
<fieldset id="template"> <!--for the duplicate-->
<div id="template"> <!--for the duplicate-->
Sample ID: <input type="text" id="SampleID" name="SampleID"></div>
<div class="_40" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label> Collection Method</label><br />
<input type="radio" id="radGrab" value="grab" name="Collection" />
<label for="radGrab">Grab</label>
<input type="radio" id="radEWI" value="EWI" name="Collection" />
<label for="radEWI">EWI</label>
</div>
<fieldset> <!--For the field blank-->
<div id="readroot" class="hidden"> <!--For the field blank-->
QA Sample ID:<input type="text" id="QASampleID" name="QASampleID">
<div class="_30" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select>
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select>
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select>
</div> <!--Fieldblank-->
</fieldset> <!--Fieldblank -->
<hr /><span id="writeroot"></span>
</div> <!--duplicate template-->
</fieldset> <!--duplicate template-->
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<button type="button" data-theme="b" data-icon="plus" id="add_FieldDup">ADD FIELD DUP</button>
I got the duplicate to work (when the field blank wasn't hidden) but I cannot get the field blank to work. Any assistance would be greatly appreciated!
You should extract your javascript from your dom, put it in separate js and make function work in any of this blocks, create class="template" block and inside give any needed interaction buttons and inputs classes so there can exist multiple parent elements with same inside structure... then cloning does not get in a way of your interaction logic.
In js go like:
$(document).ready(function() {
$(".template .interaction_button_one").on('click', function(){
//... here you go traversing like
$(this).parents('.template').find('.some_important_div').show();
})
});
Notice .on(), this is delegation, and it will give same interaction bindings to all of your elements.

Categories

Resources