getElementById() in for loop to retrieve input values - javascript

In a for loop, I am using getElementById() to retrieve several input values in javascript.
First I made a bunch of input boxes and set the different id's using a for loop.
Now I'm using a second for loop to reference those id's and retrieve their input values.
Code:
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id="+products[i][0]+" onchange=myFunction()>";
document.write(display);
}
document.write("<p id=demo></p>");
function myFunction() {
var totalVeg=0;
for (j=0;j<products.length;j++){
amount = document.getElementById(products[j][0]).value;
totalVeg += amount;
}
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
Specifically I'm having trouble with this part:
amount = document.getElementById(products[j][0]).value;
If I reference a specific input, like products[0][0], the value will be found. It is only when I try to reference an id using the "j" variable then the code stops working.
I've read through some of the other questions and answers on here but none are exactly what I want.
Thanks!

<script type="text/javascript">
var products = ["Saab","Volvo","BMW"];
for (i=0;i<3;i++)
{
var display;
display ="<input type='number' id='"+products[i]+"'onchange=myFunction(this.id)>";
document.write(display);
}
document.write("<p id=demo></p>");
var totalVeg=0;
function myFunction(_this) {
amount = parseInt(document.getElementById(_this).value);
totalVeg += amount;
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
You can take it as a reference. Hope it helps.

seem you don't have the quote around the id andbthen the id is not properly defined try this way
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id='"+products[i][0]+"' onchange=myFunction()>";
document.write(display);
}

Related

Dynamic id for HTML element which is getting created newly

I am replacing a span inside a table > td with option box.
I want to assign some unique id with dynamic value while creating the option box. How to achieve this?
Unique id is already generated , I want to set this unique id in Html while creation.
<td id="tdTest">
<span id="spanId" class="connectedSlot" style="color:rgb(27,99,173)">Enabled</span>
</td>
$("#"+spanId).replaceWith(function () {
return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});
For example , I will get some value from and assign to a variable and later assign this variable to id.
var myId = "OptionId"+test;
select class='form-control' id=myId style='width:200px;'>
Thanks
Use a variable within a string like this:
var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";
One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.
getUniqueId() is a function that will always return a unique id.
function getUniqueId() {
//get all the ids in this document
var ids = new Array();
$('[id]').each(function() { //Get elements that have an id=
ids.push($(this).attr("id")); //add id to array
});
//give some random value to uniqueId
//if this value is in ids array, then assign a different id and recheck the condition
var uniqueId;
while(true) {
uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
if($.inArray(uniqueId , ids) == -1) {
break;
}
}
return uniqueId;
}
Possible Solution:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Look into these Questions for others: link link
It's been several years since this was posted, and the accepted solution didn't work for me. Here is the syntax that did:
[id]="unqiueID"

Javascript function for form created using Javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!
Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

Contents From Two Divs to One Input Field Value

I'm trying to insert the contents of the two divs into a single input field in a form.
This is what I have so far but at the moment the only field that copies over when the onclick occurs is the edit1 div contents.
any help would be greatly appreciated.
The JAVASCRIPT:
<script language="javascript" type="text/javascript">
function copyText2() {
var output = document.getElementById("edit1","edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
</script>
The HTML:
<div id="edit1">foo</div>
<div id="edit2">bar</div>
<form>
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input onClick="copyText2()" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
Get the two contents separately, and then add them.
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + " " + output2;
Change
var output = document.getElementById("edit1","edit2").innerHTML;
into
var output = document.getElementById("edit1").innerHTML + document.getElementById("edit2").innerHTML;
That should work.
You should copy them one at a time and then concatenate
function copyText2() {
var output = "";
output += document.getElementById("edit1").innerHTML;
output += document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-tags").value = output;
}
document.getElementById("") is only using the first id string you give it. It doesn't accept multiple ids. From the Mozilla Dev docs:
id is a case-sensitive string representing the unique ID of the
element being sought.
Just have output grab the content from the first id, then from the second and append them together.

Unable to create a variable in javascript

I am creating an app that will tell you the price of a product when the barcode is scanned. Basically, when a barcode is scanned, it goes into the text field, and then based on which barcode it is, the textarea will have a price put into it via javascript. I've gotten this to work, but I can't seem to create a certain variable to save me from looking through tons of code later on.
Here is my javascript:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea').innerHTML;
if (userInput === "783466209834") {
price = "16.99";
} else {
price = "Not a valid barcode";
}
}
And here is my HTML:
<input type="text" name="text" class="textinput" id="barcode">
<input type="button" onclick="showPrice()" value="Submit">
<textarea name="" cols="" rows="" readonly="readonly" id="textarea"></textarea>
Right now, my code isn't working, but if I remove
var price = document.getElementById('textarea').innerHTML;
and replace "price" in the if statement respectively, then it works. I'm not sure why I can't create this price variable.
Because you're storing the value of the innerHTML as the variable, not storing a reference to it.
Change it to var textarea = document.getElementById('textarea'); and then textarea.innerHTML = "16.99" and so on.
If you want to work with the value of the textarea, you need to access document.getElementById('textarea').value, not innerHTML.
And, yes, as others have pointed out, you want to set the variable to reference to the element, not the value. Then you can retrieve or set the value of the element.
You are getting the innerHTML of the textarea and storing it in the variable price. Instead, you need to only store the element in the variable and then call price.innerHTML to place your result in the DOM. Like such:
function showPrice() {
var userInput = document.getElementById('barcode').value;
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}
}
EDIT: As talemyn correctly points out, you should use .value rather than .innerHTML for altering the contents of textareas. While it might look like it does the same thing, there are slight disadvantages that come with the use of .innerHTML.
You should not assign a value to price and then overwrite it... That's what your code is doing. I believe you think you are creating a storage location in the innerHTML?
Instead, just create the variable:
var price;
Run your code as you did; and then put the result into the page with
document.getElementById("text area").innerHTML = price;
You're setting the 'price' variable twice with two separate things. You're not actually changing the DOM. Instead use:
var price = document.getElementById('textarea');
if (userInput === "783466209834") {
price.innerHTML = "16.99";
} else {
price.innerHTML = "Not a valid barcode";
}

Categories