Trying to add dynamic rows (max up to 6): But it adds 2 rows at a time for some reason. So this is the order. By default 1 row is displayed, once AddPO is clicked, it inserts 2 rows, again 2 rows on button click and then ofcourse 1 since it checks for max 6 rows.
Why is it not inserting one row at a time?
Here is the code:
<script>
$(document).ready(function(){
$('#addPO').click(addPO)
});
var current = 1;
function addPO() {
current++;
if (current < 7){
var strToAdd = '<p><input id="FinalPONumber'+current+'" name="FinalPONumber'+current+'" size="20" /> <input id="FinalPOAmount'+current+'" name="FinalPOAmount'+current+'" size="20" /><input type="file" id="FinalPOFile'+current+'" name="FinalPOFile'+current+'"/></p>'
$('#mainField').append(strToAdd)
}
}
</script>
html:
<div id="mainField">
<p>
<input type="text" id="FinalPONumber1" name="FinalPONumber1" size="20" />
<input type="text" id="FinalPOAmount1" name="FinalPOAmount1" size="20" />
<input type="file" id="FinalPOFile1" name="FinalPOFile1"/>
</p>
</div>
<p>
<input type="button" id="addPO" value="Add Final PO">
Related
I have a program that I am currently trying to total.
The program is to have 10 numbers add into each text box and when the user hits the Sum button the program runs through the Add function and returns the total after the words 'Sum: '. The pages are linked with <script src="functions.js"></script> below the title tags.
Below are both pages.
function Add() {
var add_entries = 0;
for (i = 1; i <= 11; i++) {
var textentry = "Text" + i;
var x = Number(document.getElementById(textentry).value);
add_entries += x;
}
console.log(add_entries);
document.getElementById("Sum: ").innerHTML = add_entries;
}
Enter student test scores for all text boxes
<br>
<br>
<div>Blank responses will be treated as zeros.</div>
<br>
<br>
<div>Susan: <input id="Text1" type="text" /></div>
<div>Harry: <input id="Text2" type="text" /></div>
<div>Joe: <input id="Text3" type="text" /></div>
<div>Bill: <input id="Text4" type="text" /></div>
<div>Mary: <input id="Text5" type="text" /></div>
<div>Ken: <input id="Text6" type="text" /></div>
<div>Paul: <input id="Text7" type="text" /></div>
<div>John: <input id="Text8" type="text" /></div>
<div>Nora: <input id="Text9" type="text" /></div>
<div>Cindy: <input id="Text10" type="text" /></div>
<input id="Sum" type="button" value="Sum" onclick="Add()" />
<input id="Avg" type="button" value="Average" onclick="Avg()" />
<input id="High" type="button" value="Highest" onclick="Max()" />
<input id="Low" type="button" value="Lowest" onclick="Min()" />
<div>Sum: </div>
<div>Average: </div>
<div>Highest: </div>
<div>Lowest: </div>
document.getElementById("Sum: ").innerHTML = add_entries;
That's not a valid id. Give your div an id and use that.
<div id="mySum">Sum: </div>
document.getElementById("mySum").innerHTML = add_entries;
If you want to retain the "Sum:" you can use a span.
<div>Sum: <span id="mySum"></span></div>
document.getElementById("mySum").innerHTML = add_entries;
The for statement goes one step too far, if you check the console you will see an error stating something like, "TypeError: document.getElementById(...) is null", thats because its checking id="Text11"
change:
for (i = 1; i <= 11; i++)
to:
for (i = 1; i <= 10; i++)
and maybe even check that document.getElementById(textentry) doesn't return null before using it.
And of course, "use parseInt instead of Number" as Ameer said, or use a plus sign :/
+(document.getElementById(textentry).value);
for (i = 1; i <= 11; i++) 11 needs to be changed to 10 because you dont have Text11
document.getElementById("Sum: ").innerHTML = add_entries; ID is not correct
if you want the output set to your sum div you need to set an ID on it and put the id in document.getElementById(HERE)
EDIT Answer:
change this line
document.getElementById("Sum: ").innerHTML = add_entries;
to
document.getElementById("sumDiv").innerHTML = 'Sum: ' + add_entries;
and then add an ID to your div were you want the output to be
Like this <div id="sumDiv">Sum: </div>
In your for loop you're reaching 11, I can only see 10 text inputs in your HTML.
I am trying to re-create the functionality of https://chriscoyier.net/ where you have a form with radio buttons, and as you click a radio button, the text changes.
What I started with was:
window.onload=function() {
document.getElementById("hidden_elements").style.display="none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
if (this.value == "two") {
document.getElementById("hidden_elements").style.display="block";
} else {
document.getElementById("hidden_elements").style.display="none";
}
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
Input 1: <input type="text" id="intext" />
Input 2: <input type="text" id="intext2" />
Input 3: <input type="text" id="intext3" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
This allows me hide or display the div with id="hidden_elements" if input number 2 is selected.
What I want to do is hide or display the individual elements of "hidden_elements" based on the input 1, 2 or 3.
I tried changing the "hidden_elements" attributes to:
<div id="hidden_elements">
Input 1: <input type="text" name="one" />
Input 2: <input type="text" name="two" />
Input 3: <input type="text" name="three" /><br /><br />
</div>
and JS to:
var hide = document.getElementById("hidden_elements");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
function radioClicked() {
document.getElementsByName(this.value).style.display = "block"
}
But that doesn't work either.
I've tried a less appealing approach using if/else statements, but that too doesn't work.
<div id="paragraphs">
<div id="hidden_element" name="one">Paragraph 1 </div>
<div id="hidden_element" name="two">Paragraph 2 </div>
<div id="hidden_element" name="three">Paragraph 3 </div>
</div>
function radioClicked() {
if (this.value == "one") {
document.getElementById("hidden_element_one").style.display="block";
} else if (this.value == "two") {
document.getElementById("hidden_element_two").style.display="block";
} else if (this.value == "three") {
document.getElementById("hidden_element_three").style.display="block";
}
}
I've tried a few more approaches but the behaviour isn't what I want. Any idea how I can change the display from "none" to "block" based on the selected radio-button? (I know you can do it with JQuery but I'm trying to learn Javascript)
A few notes:
getElementsByName returns a list of elements. That list doesn't have a style property (the entries on the list do).
ids must be unique, you can't put the same ID on multiple elements. Use a class to group elements together.
data-* attributes would probably be a better choice than name, since you can use them on any element type.
If you want to show/hide elements based on the radio button value, you'll need to select all of the elements you show/hide, not just the one matching the radio button's value. Then loop through that list, showing/hiding depending on whether they match the selected value.
The load event happens very late in the page load cycle (e.g., right at the end). Instead of using load, put your script tags at the very end of your document, just before the closing </body> tag, and do your event hook-up immediately.
I'd probably use a class to toggle visibility rather than style.display.
You can get the attribute from an element via getAttribute.
You can use querySelectorAll to get a list of elements matching any CSS selector. Use it on document to look globally, or on a specific element to only look within that element. For instance, to get a list of elements in the document with an attribute called data-val, you'd use the CSS selector [data-val], e.g. `document.querySelectorAll("[data-val]").
Here's a version of your snippet with some minimal updates; see comments:
// I'd use querySelectorAll rather than the old-style
// forms and elements collections (but those work too)
var radios = document.querySelectorAll("#picker input[type=radio]");
// Initial value is 0, not [0]
for (var i = 0; i < radios.length; i++) { // You were missing { on this line
// Recommend modern event handling, not onclick
radios[i].addEventListener("click", radioClicked);
}
function radioClicked() {
var hidden = document.getElementById("hidden_elements");
hidden.classList.remove("hidden");
// Get all elements within it that have a data-val attribute
var list = hidden.querySelectorAll("[data-val]");
for (var i = 0; i < list.length; ++i) {
var el = list[i];
// Add/remove the hidden class depending on whether it matches
el.classList.toggle("hidden", el.getAttribute("data-val") != this.value);
}
}
.hidden {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<!-- Hide this initially with markup rather than code -->
<div id="hidden_elements" class="hidden">
<!-- Use data-val to identify them -->
Input 1: <input type="text" data-val="one" />
Input 2: <input type="text" data-val="two" />
Input 3: <input type="text" data-val="three" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
Some further changes you might make:
Wrap all the code in an IIFE so nothing is global.
Wrap the inputs and their labels in label elements, and toggle the visibility of them rather than the inputs directly.
Wrap things in containers for line breaks rather than using br.
You could do something like this :
Add a common class on the elements you want to toggle (can wrap label and field in span)
Toggle their display, can use a css class for hiding and a class same as the value of the checkbox
function radioClicked(e) {
//hide previously shown
var elem = document.getElementById("hidden_elements").getElementsByClassName("shown")[0];
if (elem) {
elem.classList.remove("shown");
elem.classList.add("hide");
}
//show currently selected
elem = document.getElementById("hidden_elements").getElementsByClassName(e.value)[0];
elem.classList.remove("hide");
elem.classList.add("shown");
}
.hide {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" onclick="radioClicked(this)" />
Item 2: <input type="radio" name="group1" value="two" onclick="radioClicked(this)" />
Item 3: <input type="radio" name="group1" value="three" onclick="radioClicked(this)" /><br />
<br />
<div id="hidden_elements">
<span class="hide one elem">Input 1: <input type="text" id="intext" /></span>
<span class="hide two elem">Input 2: <input type="text" id="intext2" /></span>
<span class="hide three elem">Input 3: <input type="text" id="intext3" /></span>
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
My solution changes the values of the radio buttons to the numeric value rather than the the text value. This enabled it to be used to select the input element by id and appending the number.
Each time radioClicked() is run it hides all the inputs and only shows the selected one. To do this I've wrapped all the inputs and their labels in span elements.
window.onload=function() {
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
var allRadio = document.querySelectorAll('#hidden_elements span');
Array.prototype.forEach.call(allRadio, function(el, i){
el.style.display="none";
});
var selectedRadio = this.value;
document.getElementById("intext" + selectedRadio).parentNode.style.display="block";
}
#hidden_elements span {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="1" />
Item 2: <input type="radio" name="group1" value="2" />
Item 3: <input type="radio" name="group1" value="3" /><br />
<br />
<div id="hidden_elements">
<span>Input 1: <input type="text" id="intext1" /></span>
<span>Input 2: <input type="text" id="intext2" /></span>
<span>Input 3: <input type="text" id="intext3" /></span><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
My solution add extra div for all inputs and id for this div
window.onload = function() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick = radioClicked;
}
function radioClicked() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
document.getElementById("hidden_" + this.value).style.display = "block"
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
<div class="hidden" id="hidden_one">Input 1: <input type="text" /></div>
<div class="hidden" id="hidden_two">Input 2: <input type="text" /></div>
<div class="hidden" id="hidden_three">Input 3: <input type="text" /><br /><br /></div>
</div>
<input type="submit" id="submitbutton" value="Send form" />
I have a row with 4 inputs:
<div id="productRow1" class="productRow">
<input type="text" name="numbers[]">
<input type="number" name="quantities[]">
<input type="text" name="levels[]">
<input type="number" name="prices[]">
</div>
I have an "Add Another Product" button and user can add another row by clicking that button. Generated row will be like this with the unique div id:
<div id="productRow2" class="productRow">
<input type="text" name="numbers[]">
<input type="number" name="quantities[]">
<input type="text" name="levels[]">
<input type="number" name="prices[]">
</div>
I have a wrapper div for all the rows like this:
<div class="input_fields_wrap">
<div id="productRow1" class="productRow">...</div>
<div id="productRow2" class="productRow">...</div>
...
</div>
How I add new rows dynamically with the unique div row id when the "Add Another Product" button is clicked:
var wrapper = $(".input_fields_wrap");
$(wrapper).append('<div ' + divId + ' class="productRow"' + '>
<input type="text" name="numbers[]"/>' +
'<input type="number" name="quantities[]"/>' +
'<input type="text" name="levels[]"/>' +
'<input type="number" name="prices[]"/>');
Also I have another text box which should show the total price instantly. So I need to get the price data of each row after each row's price is entered by user. I tried to add an event to all of my prices[] fields like this:
$(function () {
$('input[name="prices[]"]').blur(function () {
alert('testAlert');
});
});
But it didn't work. I also tried to add an onblur event to my existing and generated input fields to get the prices like this:
<input type="number" name="prices[]" onblur="calculatePrice()">
with the function:
function calculateTotal() {
alert('testAlert');
var prices = $('input[name="prices[]"]').map(function () {
alert(this.value);
return this.value;
}).get();
}
I also tried specifying input field like this: 'input[name^="prices"]' and adding the event like this:
$('input[name="prices[]"]').on('blur', function() {
alert('testAlert');
});
And adding the event by class like this after I added class='priceClass' to my price input fields:
<input type="number" name="prices[]" class="priceClass">
$('.priceClass').on('blur', function() {
alert('testAlert');
});
None of these triggered the event. So how can I add an event to all elements of a HTML input array and get the all values in the input array after the event is triggered?
You probably need something more like:
$(function(){
function getVals(){
var n = 0;
$("input[name='prices[]']").each(function(i, e){
n += +$(e).val();
});
return n;
}
$("input[name='prices[]']").change(function(){
$('#out').html(getVals());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input type='number' name='prices[]' value='10' multiple='multiple' />
<input type='number' name='prices[]' value='2' multiple='multiple' />
<input type='number' name='prices[]' value='7' multiple='multiple' />
<input type='number' name='prices[]' value='1' multiple='multiple' />
<div id='out'></div>
</body>
</html>
I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
I have html form with arrays:
<form method="post" id="formaa" name="form">
<div id="fields">
<div id="divas1" class="row">
<img src="d.jpg" /><a href="#" id="uid1" onClick="u(this);">
<img src="u.jpg" /></a><input type="text" name="ite[]" id="item" /><input type="text" name="q[]" id="quantity" class="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" class="kaina" onkeyup="update();"/><input type="text" name="sum[]" id="suma" size="10" disabled="disabled"/></div>
</div>
<br />
<input type="button" name="nw" id="new" value="ADD" onClick="naujas('laukeliai');" /><br />
Total: <input type="text" name="sumaa[]" id="suma" size="10" disabled="disabled"/>
</form>
Each time I push forms ADD button, inside the <div id="fields"> is included new div block <div id=divas(i++)> I need multiply qp[] and pr[] values and dynamicaly add to sum field, need do multiply price and quantity of each product seperately and get final each product price (not all products total).
first tried to get all values and filter these two, but couldnt figure out...
var form = document.getElementsByName('form')[0];
var inputs = form.getElementsByTagName('input');
for (var i = 0, j = inputs.length; i < j; i++) {
var element = inputs[i];
alert(element.value);
}
How to extract from this array only needed values and multiply? Thanks for advices.
Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as:
<form id="example_form">
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price"></input>
</div>
<!-- ... many more rows -->
<input type="text" disabled id="sum" name="sum"></input>
</form>
Use jQuery to make field access easier. Using JQuery, you would use the following JS:
function update() {
var total = 0;
$("#example_form div.row").each(function(i,o){
total += $(o).find(".quant").val() *
$(o).find(".price").val();
});
$("#example_form #sum").val(total);
}
This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like
$("#example_form div.row input").change(update);
Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/
you can read form array in way as below
frmRefer = document.getElementByTagName("form")[0];
for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){
alert(frmRefer.elements["ite[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){
alert(frmRefer.elements["quant[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){
alert(frmRefer.elements["pr[]"][i].value );
}