Javascript passing elementid in variable - javascript

I need to pass a variable to a javascript function which will then perform calculations and return the answer to another edit box on a form. I need to pass as I have 10 lines of edit boxes and dont want to have 10 seperate javascript functions.
function calc_totalcost(line)
{
$line_qty=line+"_qty";
$line_totcost=line+"_totcost";
$line_unitcost=line+"_unitcost";
$totcost=$line_qty.value*$line_unitcost.value;
document.getElementById('$line_totcost').value = $totcost;
}
on the html:
onchange="calc_totalcost('L1')"
So, on editbox 1 for L1_edit1 I need to send L1 to the function, which will then convert to 'L1_qty' which is an editbox (input) name where it will perform calculations using its contents. Hope that makes sense?
Thanks

You have a few issues, including the last line in the function which does not need the document.getElementById whereas all the others do need it.
function calc_totalcost(line) {
var $line_qty = document.getElementById(line+"_qty");
var $line_totcost = document.getElementById(line+"_totcost");
var $line_unitcost= document.getElementById(line+"_unitcost");
var $totcost=$line_qty.value*$line_unitcost.value;
$line_totcost.value = $totcost;
}

Related

JS Function calling displaying odd text & not working more than once

I have a problem, when I run my function "addMoney(amount)" (shown below) it works and shows the following: 100[object HTMLButtonElement]
My question is this, is there a way to get rid of the [object HTMLButtonElement] while keeping the number from moneyAmount when the function is called? And additionally, is there a way to call the function multiple times and add the money accordingly? As it only works the first time I call it, calling it more than once with the same or different amounts of moneyAmount displays no more or no less than what displays the first time.
My HTML:
<li class="item_shown" id="money">Shrill: <button class="moneyButton" id="moneyAmount">0</button></li>
Calling the function in HTML:
<a class="button" onclick="javascript:addMoney('100');">Add 100 Money</a>
My JS Function:
function addMoney(amount) {
document.getElementById('moneyAmount')
var newBalance = amount + moneyAmount;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
The text inside an element is considered to be a text node and since the button node has no other children, is the button node's first child. The text node's value (in this case "0") is the value of its nodeValue property. Assigning a new value to the nodeValue will change the text displayed. So in your case the following code should work:
function addMoney(amount) {
var node = document.getElementById('moneyAmount');
var textNode = node.childNodes[0];
var moneyAmount = parseInt(textNode.nodeValue, 10);
textNode.nodeValue = amount + moneyAmount;}
In your JavaScript, + moneyAmount; does not do anything. It returns what you see: [object HTMLButtonElement].
I think you want to add some numbers but it's not yet completely clear to me what you're trying to achieve. Could you elaborate?
Chris
EDIT:
Thank you for clarifying your question.
Try updating your function like this:
function addMoney(amount) {
var oldBalance = document.getElementById('moneyAmount').value;
var newBalance = amount + oldBalance;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
Try to find value by document.getElementById('moneyAmount').innerHTML and use some global variable say total_value to store retrieved value and then for each function call try to add the retrieved value to the previously stored value.

JavaScript populating and clearing <input> textbox

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/
You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.
Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

About a loop that creates dynamic buttons, but cannot give proper values [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript infamous Loop problem?
I am having a small issue, and it would be very nice if some of you could realize about what kind of logic is missing here, since I cannot seem to find it:
I have an array with the results of some previous operation. Let's say that the array is:
var results = [0, 1];
And then I have a bunch of code where I create some buttons, and inside a for loop I assign a different function to those buttons, depending on the position of the array. The problem is that for some reason, all the buttons created (two in this case) come out with the function assigned to the last value of the array (in this case, both would come out as one, instead of the first with 0 and the second with 1)
This is the code:
for (var i = 0; i < results.length; i++) {
var br2 = b.document.createElement("br");
var reslabel = b.document.createTextNode(Nom[results[i]].toString());
var card = document.createElement("input");
card.type = "button";
id = results[i]; // this is the problematic value.
card.onclick = newcard; // this function will use the above value.
card.value = "Show card";
divcontainer.appendChild(br2);
divcontainer.appendChild(reslabel);
divcontainer.appendChild(card);
}
As it is, this code produces as many buttons as elements in the array, each with its proper label (it retrieves labels from another array). Everything is totally fine. Then, I click the button. All the buttons should run the newcard function. That function needs the id variable, so in this case it should be:
First button: runs newcard using variable id with value 0
Second button: runs newcard using variable id with value 1
But both buttons run using id as 1... why is that?
It might be very simple, or maybe is just that in my timezone is pretty late already :-) Anyways, I would appreciate any comment. I am learning a lot around here...
Thanks!
Edit to add the definition of newcard:
function newcard() {
id = id;
var toerase = window.document.getElementById("oldcard");
toerase.innerHTML = "";
generate();
}
the function generate will generate some content using id. Nothing wrong with it, it generates the content fine, is just that id is always set to the last item in the array.
Your id is a global variable, and when the loop ends it is set to the last value on the array. When the event handler code runs and asks for the value of id, it will get that last value.
You need to create a closure to capture the current results[i] and pass it along (this is a very common pitfal, see Javascript infamous Loop problem?). Since newcard is very simple, and id is actually used in generate, you could modify generate to take the id as a parameter. Then you won't need newcard anymore, you can do this instead:
card.onclick = (function(id) {
return function() {
window.document.getElementById("oldcard").innerHTML = "";
generate(id);
};
}(results[i]));
What this does is define and immediately invoke a function that is passed the current results[i]. It returns another function, which will be your actual onclick handler. That function has access to the id parameter of the outer function (that's called a closure). On each iteration of the loop, a new closure will be created, trapping each separate id for its own use.
Before going on, a HUGE thank you to bfavaretto for explaining some scoping subtelties that totally escaped me. It seems that in addition to the problems you had, you were also suffering from scoping, which bit me while I was trying to craft an answer.
Anyway, here's an example that works. I'm using forEach, which may not be supported on some browsers. However it does get around some of the scoping nastiness that was giving you grief:
<html>
<body>
<script>
var results = [0,1];
results.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = "Show card";
document.body.appendChild(card);
});
function newcard(x) {
alert(x);
}
</script>
</body>
</html>
If you decide to stick with a traditional loop, please see bfavaretto's answer.

How to use parameters from another function [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Get actual HTML values using javascript
so i have two problems here. let me explain what i am trying to do first. I have a page that has values that change on it, however i want to grab the values before they change, keep them, and then once a button is pushed, change the html to the original html. Now first of all my biggest problem is that when i try to uncomment the initial2 function, it just doesnt work. it brings me to the webpage then for some reason the html url tries to change and it says it can not find the page. the second, and more understandable problem for me, is that the function previousaccept i cant get to use the values from the previousnames function.
function previousnames()
{
name= document.getElementById('name').innerHTML;
imagetitle= document.getElementById('imagetitle').innerHTML;
location=document.getElementById('location').innerHTML;
similarities = document.getElementById('similarities').innerHTML;
type = document.getElementById('type').innerHTML;
cost = document.getElementById('cost').innerHTML;
date = document.getElementById('date').innerHTML;
pictureid = document.getElementById('pictureid').src;
}
function previousaccept(name,imagetitle,location,similarities,value,type,cost,date,pictureid)
{
document.getElementById('name').innerHTML = name;
document.getElementById('location').innerHTML = location;
document.getElementById('similarities').innerHTML = similarities;
document.getElementById('type').innerHTML = type;
document.getElementById('cost').innerHTML = cost;
document.getElementById('date').innerHTML = date;
window.alert(pictureid);
document.getElementById('pictureid').src = pictureid;
}
window.onload=initial();
function initial()
{
myvalues;
previousnames;
}
/*
function initial2()
{
myvalues;
previousnames();
}*/
If you set the location (which is window.location), then the browser will go to a new web page. That's what you're doing in the previousnames() function with this line:
location=document.getElementById('location').innerHTML;
If you're trying to have a global variable named location, then give it a different name that isn't already used by the browser.
Also, you should explicitly declare any global variables you intend to use outside of your functions rather than use implicitly declared variables like you are which makes your code very prone to errors.
I think this will do what you want. The key is to make sure that the scope of the variables you are trying to store is such that the functions have access to them all. I do this by defining an empty object dataStore at the start of the onload function, and also defining the 2 other functions within the onload function. Putting all the stored data in a single object is convenient and avoids naming problems (such as the window.location problem noted by the previous answer.)
window.onload = function() {
var dataStore = {};
function getInitialData() {
dataStore = {
name: document.getElementById('name').innerHTML,
imagetitle: document.getElementById('imagetitle').innerHTML,
// and so on...
}
}
function resetData() {
document.getElementById('name').innerHTML = dataStore.name;
document.getElementById('imagetitle').innerHTML = dataStore.imagetitle;
// and so on...
}
getInitialData();
//... then later when you want to reset all the values
resetData();
}​

Cloned row requesting same function [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});​

Categories

Resources