onClick JavaScript doesn't work at the first access (page access) - javascript

I have created a JavaScript function that doesn't work when we first access the web page. It will only work either by refreshing the page or accessing it for the second time.
How do I make sure that it works even when we access the page for the first time?
Here is the code:
<script type="text/javascript">
/*--adding/subtracting no. of seats and price-- */
function calculateSeat()
{
var nums = [document.getElementById('number_seat0').value, document.getElementById('number_seat1').value,document.getElementById('number_seat2').value,document.getElementById('number_seat3').value,document.getElementById('number_seat4').value];
var num = 0;
for (i=0; i < nums.length; i++) {
num += +nums[i];
}
document.getElementById('total_seat').value = num;
document.getElementById('total_amount').value = parseFloat(num * <?php echo $_SESSION['price'] ;?>).toFixed(2);
};
</script>

Check below sample
<script type="text/javascript">
function calculateSeat() {
// your php variables
var phpPrice = parseInt('<?php echo $_SESSION['price'] ;?>');
// shortcut
var $byId = document.getElementById; //faster that querySelector
// list of your DOM elements with ids
var ids = ['number_seat0', 'number_seat1', 'number_seat2', 'number_seat3', 'number_seat4'];
// function that will be used in [].reduce
// to calculate your result
function getSum(total, id) {
return total + ( +$byId( id ).value );
};
// total number
// Array.reduce docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var result = ids.reduce(getSum);
$byId('total_seat').value = result;
$byId('total_amount').value = (result * phpPrice).toFixed(2);
}
</script>

I have actually managed to resolve this issue by simply placing the script at the bottom of the body tag instead of the head (note: where it was previously).

Related

How can i use script parameters into my js file?

I have this script code:
<script src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?
Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".
I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.
You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();

Javascript for loop function array

I'm bit of a javascript newbie - I'm trying to make a function that when I click a button it will call out a single object out of my array, in order.
all it does is display "ee".
Of course, you are looping through the whole array and assigning each item to the innerHTML of that one element - and only the last one will stay there and show up.
What I want it to do is when I click the button to display "aa" then when I press it again to display "bb" instead of "aa" and so on.
Then you can't use a for-loop, but have to keep track of the counter manually and execute only one step per invocation of call.
var myArray = ["aa","bb","cc","dd","ee"];
var i=0;
function call() {
document.getElementById("placeDiv").innerHTML = myArray[i];
if (i < myArray.length-1)
i++;
else
i = 0; // restart, but you may as well show an error message
}
You want a closure.
var call = (function() {
var i = 0,
entries = ["aa", "bb", "cc", "dd", "ee"];
return function() {
return entries[i++ % entries.length];
};
})();
This keeps i and entries as private values, and returns a function that goes to the next entry in the list each time it is called.
Try this:-
You are looping through on each click and assigning value to the element innerHTML so it will always have only the last value from the array.
Demo
var myArray = ["aa","bb","cc","dd","ee"];
var i = 0;
function call(){
if(myArray.length <= i) i=0;
document.getElementById("placeDiv").innerHTML = myArray[i++];
}
if you don't want to use a global variable you can use this way too.
http://jsfiddle.net/zZ4Rm/
Use shift method on array to get the first item and then push it back tht end of the array for the cycle to happen.
var myArray = ["aa","bb","cc","dd","ee"];
function call(){
var val = myArray.shift();
myArray.push(val);
document.getElementById("placeDiv").innerHTML = val;
}
You are overwritting your placeDiv with innerHTML.
Try using:
function call(){
var yourVar= document.getElementById('placeDiv');
for (var i=0; i < myArray.length; i++) {
yourVar.innerHTML = yourVar.innerHTML + myArray[i];
}
}
<script type="text/javascript">
var myArray = ["aa","bb","cc","dd","ee"],
num=0;
function call() {
document.getElementById("placeDiv").innerHTML = myArray[num];
num++;
};
</script>
<button onclick="call()">Click!</button>
<div id = "placeDiv"></div>

Javascript Dynamic GetElementByID

I would like to use the same function on two different elements without duplicating my code and changing the id. I'd like to pass the ID as a parameter into my function but it's not working.
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
Any ideas?
Looks to me as if the error is somewhere else, specificially in this line:
selected[count] = selObj.options.value;
Shouldn't that be:
selected[count] = selObj.options[x].value;
or (without the need for an extra "count" variable)
selected.push( selObj.options[x].value );
(Furthermore, you're missing a var in front of x = 0, thus making x a global variable.)

Please assist me with this simple script

I am new to JavaScript and would like to ask for some help with my simple script.
What I am trying to do is to retrieve and display the values of all list item elements in the unordered list with the help of the (for) loop. I was able to get the script display all list items in the alert window one by one. But the problem is that I need values of all list elements displayed in a table row way. Like this:
Monday
Tuesday
Wednesday
.......
Here is what I have in my script:
<script language="JavaScript">
<!--
function process() {
a = document.getElementsByTagName('li')
for (i = 0; i < a.length; i++) {
alert(a[i].childNodes[0].nodeValue);
}
}
//-->
</script>
And here is HTML code:
<body>
<ul>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
</ul>
<input type="button" value="Submit" onclick="process()" />
</body>
If that's possible at all would anyone please also explain where I am wrong in my script? Why all 3 list item values can't be shown in the alert window at once?
Thanks a lot!
First, create a string variable: var all_at_once = "". Then, add the contents of the nodeValue. Finally, alert this variable:
function process(){
var a = document.getElementsByTagName('li')
var all_at_once = "";
for(i=0;i<a.length;i++){
all_at_once += a[i].childNodes[0].nodeValue + " ";
}
alert(all_at_once);
}
The alert shows repeatedly because that is what a for loop does... it loops! The loop will iterate over the array of elements returned by getElementsByTagName, executing the loop body once for each element in that array.
If you wanted to display one alert, an option would be to build up a string containing the appropriate text, and alert it afterwards:
var yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
Some other notes on your code... you should almost always declare variables with the var keyword to prevent them leaking into the global scope. You should also always end lines with semi-colons:
function process(){
var a = document.getElementsByTagName('li'),
yourString = "";
for(i=0;i<a.length;i++){
yourString += a[i].childNodes[0].nodeValue;
}
alert(yourString);
}
<script language="JavaScript">
<!--
function process(){
var data = '';
a=document.getElementsByTagName('li')
for(i=0;i<a.length;i++){
data = data + '\n' +(a[i].childNodes[0].nodeValue);
}
alert(data);
}
//-->
</script>
You need to call alert only once if you need 1 popup with all the text.
function process()
{
var a = getElementsByTagName('li'),
text = '';
for( i = 0; i < a.length; i++ )
{
text += a[i].childNodes[0].nodeValue + '\n';
}
alert( text );
}
You can process the days in whatever manner you like by storing them in an array first, and then iterating:
var days = new Array();
var a = document.getElementsByTagName('li')
for(var i = 0; i < a.length; i++) {
days.push(a[i].childNodes[0].nodeValue);
}
for (i=0; i < days.length; i++) {
// process the day
}
See: http://jsfiddle.net/jkeyes/Cfg4k/ for a working example.
These few adjustments to your function should produce the result you want. Good luck!
What changed: 1) Set up an empty string var 2) Instead of alerting each value, just append them to the string var you created earlier 3) Finally, alert the newly created (concatenated) string!
function process() {
a = document.getElementsByTagName('li');
var days = new String("");
for (i = 0; i < a.length; i++) {
days = days+(a[i].childNodes[0].nodeValue)+"\n";
}
alert(days);
}
Now I see there have been tons of answers since opening this thread... but maybe all the different solutions will help you in different ways.

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Categories

Resources