http://www.quirksmode.org/dom/domform.html
I am trying to implement this extend form function in my project. But the field names cannot be located (the console log returns "undefined"), until I place an input field out of the divs and directly under the parent span tag. I'm not sure how the field names can be located and named accordingly as I intend to keep the divs.
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="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">Grade</label>
<select name="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 = "data[Student][" + counter + "][" + theName + "]";
console.log(newField[i].name);
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
childNodes returns only direct children. It will find only elements with name attributes at the top level. To find all descendant elements with names as you want, try
var newField = newFields.querySelectorAll('[name]');
Minor points:
Although in this case you don't need to use either, you should use .children instead of .childNodes. The latter will visit white-space nodes, which won't hurt anything but isn't what you want.
You are missing brackets around the body of the if (theName) statement, meaning the console.log is being executed each time through the loop, even when a white-space node is being visited. To avoid such problems, set up your editor to indent property, and/or run a linter across your code.
if (theName) {
newField[i].name = "data[Student][" + counter + "][" + theName + "]";
console.log(newField[i].name);
}
I'd suggest naming your variables a bit more clearly. You have a variable named newFields which is a single span, and you have a variable called newField which is a collection of fields.
Related
Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help
I need help extending this JavaScript (borrowed from https://www.quirksmode.org/dom/domform.html):
var appCounter = 0;
function anotherApp() {
appCounter = appCounter + 1;
var newAppField = document.getElementById("keyApp").cloneNode(true);
newAppField.id = '';
newAppField.style.display = 'block';
var newApp = newAppField.childNodes;
for (var i = 0; i < newApp.length; i++) {
var theName = newApp[i].name
if (theName) {
newApp[i].name = theName + appCounter;
}
}
var insertApp = document.getElementById('keyApp');
insertApp.parentNode.insertBefore(newAppField, insertApp);
document.getElementById('appCount').value = appCounter
}
This works fine when element in my form is:
<div id="keyApp" style="display:none">
<input type="text" name="application" id="application">
<input type="text" name="usage" id="usage">
<\div>
But when I add div's around the inputs (bootstrap styling reasons) I loose the ability to update the input names:
<div id="keyApp" style="display:none">
<div class="col-md-2">
<input type="text" name="application" id="application">
</div>
<div class="col-md-2">
<input type="text" name="usage" id="usage">
</div>
<\div>
How do I extend the script to modify the input names in these new div's?
Since there is now another layer, you need to get newApp[i].childNodes[0] now in order to get the actual input elements.
newApp now holds a list of the div elements with col-md-2 styling, and you need to get the children inside of these div elements.
So I'm trying to calculate sales tax for a project and I can't get it to work. Needless to say, I'm still learning javascript. Here's how it works: If the buyer selects New Jersey, I want to apply a 7% sales tax to the order. Everywhere else goes to zero.
Here's a link to the jsFiddle project: https://jsfiddle.net/JohnOHFS/hpdnmjfL/
Here's my basic form HTML (skipping the opening and closing tags, etc.)
<div id="public">
<div class="row">
<div class="col-xs-7 col-md-7">
<div class="form-group">
<label for="city">CITY</label>
<input type="text" size="20" autocomplete="off" class="city input-small form-control" placeholder="CITY"/>
</div>
</div>
<div class="col-xs-4 col-md-4">
<div class="form-group">
<label for="state">STATE</label>
<select class="form-control" id="state" onChange="taxRate()">
<option value="">N/A</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-5 col-md-5">
<div class="form-group">
<label for="zipCode">ZIP CODE</label>
<input id="zip" type="text" size="6" autocomplete="off" class="zipcode form-control" placeholder="ZIP CODE"/>
</div>
</div>
</div>
</div> <!-- Closes Public -->
<div class="row">
<div class="col-xs-7 col-md-7">
<label>ORDER INFORMATION</label>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7 col-md-offset-1">
<label>SUBTOTAL: <b>$<span id="order_subtotal">100</span></b></label>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7 col-md-offset-1">
<label>TAXES: <b><span id="order_tax" type="text" value=""></span></b></label>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7 col-md-offset-1">
<label>ORDER TOTAL: <b><span id="order_total" type="text" value=""></span></b></label>
</div>
</div>
Here's the Javascript:
function taxRate() {
var tax_rate = .07;
var order_taxes = 0;
var subtotal = document.getElementById("order_subtotal").value;
subtotal = parseInt(subtotal);
var total = 0;
var state = document.getElementById("state").value;
var selection = state.options[state.selectedIndex].value;
if (selection == 'New Jersey') {
order_taxes += tax_rate * subtotal;
}
if (selection == 'else') {
order_taxes = 0;
}
if (selection == 'New Jersey') {
tax_percent = tax_rate * 100;
}
if (selection == 'else') {
tax_percent = 0;
}
var el = document.getElementById('order_tax');
el.textContent = order_taxes;
var total = subtotal + order_taxes;
var el1 = document.getElementById('order_total');
el1.textContent = total;
}
Here are my questions.
1. What am i doing wrong?
2. How do I pass tax_percent from this javascript into the html for submittal to Stripe?
Thanks!
The first problem with your fiddle is that the taxRate() function is not a global function and so it can't be called from an inline html attribute event handler. This is because by default JSFiddle wraps the JS in an onload handler. Use the JS settings menu (from top-right corner of the JS window) to change the "load type" to one of the "no wrap" options.
Then you've got a problem getting the order total value, because you try to get the element .value when it is a span, so you need to use .innerHTML.
The next thing is that your state variable is set equal to the value of the current selection of the select element. So it will be 'NJ', or 'AK', etc. (Or an empty string if nothing is selected.) So when you try to set the selection variable to state.options[state.selectedIndex].value that won't work because state is a string. Test your existing state variable against 'NJ':
if (state == 'NJ')
You also have a test if (selection == 'else') which won't do anything because even if your selection variable worked its value would never be the string 'else'. I think you just want an else statement there, except that what that block actually does is just set order_taxes = 0 and order_taxes has already been set to a default of 0 at the point of declaration. So you don't need that part at all.
Then you've got another if testing for New Jersey that could be combined with the first one. It's setting a tax_percent variable that isn't declared, so add a declaration for that with var at the top of your function.
Also, because of the way JS does floating point maths, 100 * 0.07 comes out to be 7.000000000000001. You probably want to round that off to two decimal places for the cents amount (which in this case would be no cents, but obviously if the order total wasn't such a round number you might get some number of cents in the taxes).
How do I pass tax_percent from this javascript into the html for submittal to Stripe?
One way is to add a hidden input to your form and set its value from JS:
<input type="hidden" id="tax_percent" name="tax_percent">
document.getElementById('tax_percent').value = tax_percent;
Putting that all together:
function taxRate() {
var tax_rate = .07;
var order_taxes = 0;
var tax_percent = 0;
var subtotal = document.getElementById("order_subtotal").innerHTML;
subtotal = parseInt(subtotal);
var total = 0;
var state = document.getElementById("state").value;
if (state === 'NJ') {
order_taxes += +(tax_rate * subtotal).toFixed(2);
tax_percent = +(tax_rate * 100).toFixed(2);
}
var el = document.getElementById('order_tax');
el.textContent = order_taxes;
var total = subtotal + order_taxes;
var el1 = document.getElementById('order_total');
el1.textContent = total;
document.getElementById('tax_percent').value = tax_percent;
}
Demo: https://jsfiddle.net/hpdnmjfL/5/
<div class="form-inline">
<div class="form-group col-lg-4">
<label>Select Item:</label>
<div id="field1">
<select class="form-control" name="item_1">
<?php if($item !=0){foreach ($item as $list_item){?>
<option value="<?php echo $list_item['item'];?>">
<?php echo $list_item[ 'item'];?>
</option>
<?php }}else {?>
<option value="">No Items Available</option>
<?php }?>
</select>
</div>
</div>
<div class="form-group col-lg-2">
<label>Quantity:</label>
<div id="field2">
<input type="number" min="1" class="form-control input-md" name="quantity_1" />
</div>
</div>
<div class="form-group col-lg-3">
<label>Cost(per piece):</label>
<div id="field3">
<input type="number" min="1" class="form-control input-md" name="cost_1" />
</div>
</div>
<div class="form-group col-lg-3" style="margin-top:25px">
<div id="field4">
<button id="addmore" onclick="add();" class="btn add-more" type="button">+</button>
</div>
</div>
</div>
I have these three fields('item, quantity and cost') and these three fields are added incrementally on clicking + button but i am having removing these buttons on - click.
I simply need these three input fields to be added at one click and remove these fields on one click as well. also these fields name should be incremented.
<script>
function add() {
i++;
var div1 = document.createElement('div');
div1.innerHTML = '<select class="form-control" name="item_' + i + '"> <option value=""></option></select>';
document.getElementById('field1').appendChild(div1);
var div2 = document.createElement('div');
div2.innerHTML = '<input type="number" min="1" class="form-control input-md" name="quantity_' + i + '" />';
document.getElementById('field2').appendChild(div2);
var div3 = document.createElement('div');
div3.innerHTML = '<input type="number" min="1" class="form-control input-md" name="cost_' + i + '" />';
document.getElementById('field3').appendChild(div3);
var div4 = document.createElement('div');
div4.innerHTML = '<button id="remove" onclick="remove_btn(this)" class="btn remove" type="button">-</button>';
document.getElementById('field4').appendChild(div4);
}
</script>
There are several issues:
Avoid putting blobs of HTML in your javascript, put your HTML in the HTML file.
Avoid IDs, particularly when they will certainly be duplicated. Duplicate IDs are illegal. Only the first one can be found with a lookup.
Avoid concatenating together strings of text to generate your HTML. It is a too easy to make a mistake and put an XSS vulnerability in your code that way.
(function($) {
"use strict";
var itemTemplate = $('.example-template').detach(),
editArea = $('.edit-area'),
itemNumber = 1;
$(document).on('click', '.edit-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[name]').attr('name', function() {
return $(this).attr('name') + '_' + itemNumber;
});
++itemNumber;
item.appendTo(editArea);
});
$(document).on('click', '.edit-area .rem', function(event) {
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
}(jQuery));
.hidden { display: none; }
.formfield { float: left; }
.example-template { clear: left; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hidden">
<div class="example-template">
<div class="formfield"><input placeholder="Name" name="name"></div>
<div class="formfield"><input placeholder="Addr" name="addr"></div>
<div class="formfield"><input placeholder="Post" name="post"></div>
<div class="formfield"><button class="del">-</button></div>
</div>
</div>
<div class="edit-area">
<div class="controls">
<button class="add">+</button>
<button class="rem">-</button>
</div>
</div>
This works by first grabbing the row template out of the hidden div element, and storing it in a variable. Each time it needs to make a new row, it clones the template and updates it. It updates it by adjusting the name element as required, appending "_" and a number. Once it has customized this copy of the template, it appends it to the edit area.
You can remove elements with a reference to the parent using similar syntax with the following:
var childElement = document.getElementById("myChildElement");
document.getElementById("myElement").removeChild(childElement);
Similar to what is described here: http://www.w3schools.com/js/js_htmldom_nodes.asp
Also, consider a toggle on the CSS style property: "display: none;"
I have a block of form elements which I would like to clone and increment their ID's using jQuery clone method. I have tried a number of examples but a lot of them only clone a single field.
My block is structured as such:
<div id="clonedInput1" class="clonedInput">
<div>
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
</div>
Obviously elements are lined up a lot better but you get the idea.
I would like to keep the id structure i.e. category1, subcategory1 etc as I use these to dynamically display select options based on the parent selection so if its possible to have each cloned block like category1/category2/category3 etc that would be great.
HTML
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
JavaScript - Jquery v1.7 and earlier
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length) but it works ;)
JAvascript - JQuery recent (supporting .on())
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
working example here
Another option would be to use a recursive function:
// Accepts an element and a function
function childRecursive(element, func){
// Applies that function to the given element.
func(element);
var children = element.children();
if (children.length > 0) {
children.each(function (){
// Applies that function to all children recursively
childRecursive($(this), func);
});
}
}
Then you can make a function or three for setting the attributes and values of your yet-to-be-cloned form fields:
// Expects format to be xxx-#[-xxxx] (e.g. item-1 or item-1-name)
function getNewAttr(str, newNum){
// Split on -
var arr = str.split('-');
// Change the 1 to wherever the incremented value is in your id
arr[1] = newNum;
// Smash it back together and return
return arr.join('-');
}
// Written with Twitter Bootstrap form field structure in mind
// Checks for id, name, and for attributes.
function setCloneAttr(element, value){
// Check to see if the element has an id attribute
if (element.attr('id') !== undefined){
// If so, increment it
element.attr('id', getNewAttr(element.attr('id'),value));
} else { /*If for some reason you want to handle an else, here you go*/ }
// Do the same with name...
if(element.attr('name') !== undefined){
element.attr('name', getNewAttr(element.attr('name'),value));
} else {}
// And don't forget to show some love to your labels.
if (element.attr('for') !== undefined){
element.attr('for', getNewAttr(element.attr('for'),value));
} else {}
}
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined){
element.val('');
}
}
Then add some markup:
<div id="items">
<input type="hidden" id="itemCounter" name="itemCounter" value="0">
<div class="item">
<div class="control-group">
<label class="control-label" for="item-0-name">Item Name</label>
<div class="controls">
<input type="text" name="item-0-name" id="item-0-name" class="input-large">
</div>
</div><!-- .control-group-->
<div class="control-group">
<label for="item-0-description" class="control-label">Item Description</label>
<div class="controls">
<input type="text" name="item-0-description" id="item-0-description" class="input-large">
</div>
</div><!-- .control-group-->
</div><!-- .item -->
</div><!-- #items -->
<input type="button" value="Add Item" id="addItem">
And then all you need is some jQuery goodness to pull it all together:
$(document).ready(function(){
$('#addItem').click(function(){
//increment the value of our counter
$('#itemCounter').val(Number($('#allergyCounter').val()) + 1);
//clone the first .item element
var newItem = $('div.item').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#itemCounter').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
}
);
// Finally, add the new div.item to the end
newItem.appendTo($('#items'));
});
});
Obviously, you don't necessarily need to use recursion to get everything if you know going in exactly what things you need to clone and change. However, these functions allow you to reuse them for any size of nested structure with as many fields as you want so long as they're all named with the right pattern.
There's a working jsFiddle here.
Clone the main element, strip the id number from it.
In the new element replace every instance of that id number in every element id you want incremented with the new id number.
Ok, here's a quicky code here.
Basically, this part is the most important:
(parseInt(/test(\d+)/.exec($(this).attr('id'))[1], 10)+1
It parses the current id (using RegEx to strip the number from the string) and increases it by 1. In your case instead of 'test', you should put 'clonedInput' and also not only increase the value of the main element id, but the three from the inside as well (category, subcategory and subsubcategory). This should be easy once you have the new id.
Hope this helps. :)
Add data attribute to the input to get the field name, increment the value with variable.
html :
<td>
<input type="text" data-origin="field" name="field" id="field" required="" >
<div role="button" onclick='InsertFormRow($(this).closest("tr"),"tableID","formID");' id="addrow"> + </div>
</td>
and put this javascript function
var rowNum = 1;
var InsertFormRow = function(row, ptable, form)
{
nextrow = $(row).clone(true).insertAfter(row).prev('#' + ptable + ' tbody>tr:last');
nextrow.attr("id", rowNum);
nextrow.find("input").each(function() {
this.name = $(this).data("origin") + "_" + rowNum;
this.id = $(this).data("origin") + "_" + rowNum;
});
rowNum++;
}