I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.
Here is the input code:
<input type="number" id="id_[SOME_ID_HERE]" value="0">
and the loop used to update the values.
for (var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(3)).value = 5;
}
jsfiddle: http://jsfiddle.net/zkTud/
EDIT: Seems like it doesn't work with type="text" as well...
EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.
Thanks anyways!
I really appreciate the help I'm getting in this site! :)
The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(5)).value = 5;
}
Here's an updated fiddle.
The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.
Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):
document.getElementById("i" + val.substring(3)).value = 5;
demo http://jsfiddle.net/bY4EV/6/
sustring(3) gives d_1 : How to substring in jquery
hope this helps
code
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id_" + val.substring(5)).val("5");
}
Check this, JSFiddle , Updated and corrected your problem.
Code:
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id" + val.substring(4)).val( "5");
}
Related
Not sure why I'm having a hard time with this. I think it's getting late in the day probably but --
I'm pulling database values into an array. The current array is: [1,3]. I'm then stepping through the array and appending a prefix to the values (in this case: "&Plantkey=") in order for the final string to have the format of:
&Plantkey=1&Plantkey=3
Here's my code so far:
if (array[a].ParameterName == "Plantkey") {
var plantKey = array[a].ParameterValue;
var plantTemp = [];
plantTemp = plantKey.split(",");
for (var p = 0; p < plantTemp.length; p++) {
var plantKeyString = ("&Plantkey=" + plantTemp[p]);
}
}
I'm only getting the last array value (&Plantkey=3). With javascript, it doesn't like me instantiating the "var plantKeyString" and adding the "+=" operator. If I instantiate the array above the for loop, like so:
var plantKeyString;
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
Then I end up with a longer string, including the array values I want but it also pulls in the "undefined" value that it finds at the beginning so it looks like this:
undefined&Plantkey=1&Plantkey=3
I could easily look for the "undefined" and remove it but I'm sure the problem is with the loop iteration, not the data, obviously.
Any help would be greatly appreciated! Thanks!
The reason you are getting only the last value in the first case is because you are redeclaring a new plantKeyString for each loop hence only the last declaration stays.
with the second solution just do the following and it should work:
var plantKeyString="";
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
The reason you were getting the undefined at the beginning of your final result was because 'plantKeyString' is 'undefined' as you have not given it a value. In javascript all variables are undefined till you give them a value. So in the solution that I have provided you are just instantiating it with an empty string.
You can do it in a succinctly way simply using array join() method and add &Plantkey= at first as follows:
var plantKeyString = '&Plantkey=' + array.join('&Plantkey=');
For an [1,3] array this code produces what you expect: &Plantkey=1&Plantkey=3, try with this code sample:
var array = [1,3];
var plantKeyString = '&PlantKey=' + array.join('&PlantKey=');
alert(plantKeyString);
See join() description here
I have indexed a bunch of inputs in my html form.
I want to loop through the inputs and create an array. From that array I want to collect the total (sum) of the fields and finally append another HTML input to display that total.
I know how to do this in PHP but I am struggling with JavaScript and I need it done client side.
I have tried to construct as much of this as possible. Here is a jsFiddle:
Here is my html:
<div style="padding:5px;clear:both;"><input type="text" name="total_inkind" id="total_inkind" placeholder="$" onchange="calcInKind()"></div>
and Javascript:
function calcInKind() {
var runningTotal = 0;
var i = 0;
for (var i = 0; document.getElementById('inkind').value; i++){
if(document.getElementById('inkind').value != ''){
$gwyl_gr = document.getElementById('inkind').value;
$runningTotal = parseFloat($runningTotal) + parseFloat($gwyl_gr);
}else{
$gwyl_gr = 0;
}
i = i++;
}
document.getElementById('total_inkind').value = $runningTotal;
}
For something as simple as a sum of all the form elements, you don't really need an array unless you want to manipulate every value in more ways than one. You can however loop over every input you had in the form, taking its value and adding it to the total.
Looking at your code however, I have to remark that Javascript does not require variables to be preceded by a $ unlike PHP. You however have the opportunity to use them, which JQuery users often do, to denote that their variable is in fact a JQuery variable.
I forked your JSFiddle and rewrote some things to get it working as the question states: JSFiddle
function sumTheInkinds() {
var runningTotal = 0;
var ourlist = document.getElementsByClassName("inkind");
for (var i = 0; i < ourlist.length; i++) {
if (ourlist[i].value != '') {
try {
runningTotal = runningTotal + parseFloat(ourlist[i].value);
} catch (err) {
alert ("Value was not a float!");
}
}
}
document.getElementById('total_inkind').value = runningTotal;
};
document.getElementById("runcalc").onclick = sumTheInkinds;
My implementation however relies on a button press which may not be intended, which can easily be changed back to onchange by applying this:
var inks = document.getElementsByTagName("inkind");
for (var i=0;i<inks.length;i++) {
inks.onchange = sumTheInkinds;
}
Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});
I'm trying to load X amount of <li>'s into a <ul> via a for loop in a jquery function, and while I think I've got the syntax about right I'm not getting anything loading. (no problem with loading a single <li>, but none for multiples with the method I've tried)
Initially I attempted to pass a variable into the loop to determine the amount of increments: var peekListAmount = 5;
That didn't work so I went for a bog-standard loop incrementer. That doesn't work either so, after searching here and getting close, I have put together a fiddle to see if someone can point out what I'm doing wrong: http://jsfiddle.net/janowicz/hEjxP/8/
Ultimately I want to use Knockout.js to dynamically input a number to pass to the loop amount variable, but 1st things 1st.
Many thanks in advance.
When you do:
var peekListItem = $('<li>...</li>');
you're creating a single instance of an <li> node, encapsulated in a jQuery object.
Appending an already-present node to the DOM just removes it from its current place in the DOM tree, and moves it to the new place.
You need to create the node inside the loop, not outside, otherwise you're just re-appending the same node each time, not a copy of that node.
In fact, given you're not manipulating that node, you can just put the required HTML directly inside the .append() call without wrapping it in $(...) at all:
$(function() {
var peekList = $('<ul class="peekaboo-list">').appendTo('div.peekaboo-wrap');
function addLiAnchorNodes(nodeAmount) {
var html = '<li>' +
'<p class="peekaboo-text"></p></li>';
for (var i = 0; i < nodeAmount; ++i) {
peekList.append(html);
}
}
addLiAnchorNodes(5);
});
See http://jsfiddle.net/alnitak/8xvbY/
Here is you updated code
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
var peekListItem = '<li><p class="peekaboo-text"></p></li>';
//var peekListAmount = 5;
var tmp = '';
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
tmp += peekListItem;
}
peekList.append(tmp);
$('div.peekaboo-wrap').append(peekList); // This bit works fine
}
addLiAnchorNodes();
});
This should work. Instead of appending the list item in each loop, append the list only once at the end.
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
peekList.appendTo('div.peekaboo-wrap');
var addLiAnchorNodes = function (nodeAmount){
var list = "";
for (var i = 0; i < 10; i++){
list += '<li>Sample<p class="peekaboo-text"></p></li>';
}
peekList.append(list);
}
addLiAnchorNodes();
});
Here is the updated fiddle
Try this:
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
$(peekList).appendTo('div.peekaboo-wrap'); // This bit works fine
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
var peekListItem = $('<li><p class="peekaboo-text"></p></li>');
peekListItem.appendTo(peekList);
}
}
addLiAnchorNodes();
});
I've run into a problem here. I have a text box that is only returning an empty string.
var myFields = [];
for(var i = 0; i < fields.length; i++){
var newField = document.createElement('input');
newField.type = 'text';
prompt.innerHTML += fields[i] + ': ';
prompt.appendChild(newField);
prompt.innerHTML += '<br>';
myFields.push(newField);
}
var finishPrompt_Action = function(){
var results = {}
for(var i = 0; i < myFields.length; i++){
console.log(fields[i], myFields[i], myFields[i].value);
results[fields[i]] = myFields[i].value;
}
container.removeChild(shield);
container.removeChild(prompt);
callback(results);
}
So, in the second function myFields[i].value returns an empty string.
Although myFields[i] does point to the correct input element.
Anyone got any ideas?
This is the only code that touches the textbox, and I type in the value using my keyboard.
It's sensible to change prompt to something else, to prevent confusion with javascripts native prompt function. Furthermore it looks like your code can work. See this jsfiddle
promptDiv.innerHTML += '<br>';
This was the problem line. If anyone knows why or how this was breaking the code I would REALLY like to know. Commenting out this single line, fixes the problem.
Thanks,
Greg