Calculation help needed in javascript - javascript

Why won't this short example work? I am trying to get a total calculated on the fly, but it seems the function's aren't updating the total box.
In my actual work I am using radio buttons to update the pricing on the fly (rather than the button shown here), which each have an onclick function applied.
http://jsfiddle.net/jvEDt/1/
Any help would be amazing! Thanks very much
Your order total: <input type="text" id="totalbox" name="totalbox" size="10" maxlength="10" readonly="readonly" value="0.00" /><br>
<input name="Order" type="submit" value="Order" onclick ="JavaScript: calculateTotal();">
function calculateTotal()
{
var total = "5.00";
var totalbox = document.getElementById('totalbox');
totalbox.value = "£" + total;
}

There are different settings in jsFiddle how the javascript should be treated.
onLoad
This executes the script when the body has loaded:
<body onLoad="<your script>">
No wrap - in head
This inserts the script in the head section:
<head>
Your script
</head>
In your case you don't want to execute the script but rather include it on the page so that it's globally available. No wrap - in head is the setting you should use.

You can define your function at run-time:
calculateTotal = function()
{
// your code
}
Or you can change the place Javascript is loaded in the jsfiddle to No wrap as said in other answers.
Check this thread about run-time and parse-time defined functions: var functionName = function() {} vs function functionName() {}

additionaly:
<input name="Order" type="button" value="Order" onclick="calculateTotal();">
No spaces, no JavaScript: etc.

Related

Changing Input Text Value JS

Breadit here and I have a problem. I tried to look everywhere but can't find a single answer that will work. I am trying to make a button which will square the first tag and will print the output on the second tag.
JavaScript:
function square() {
var a=document.getElementById("inputSquare");
var b=a*a;
document.getElementById("outputSquare").value=b;
}
HTML:
<input type="number" id="inputSquare">
<button onclick="square()">=</button>
<input type="number" id="outputSquare" readonly>
That is my problem.
Try this:
function squaree() {
var a=document.getElementById("inputSquare").value;
var b=a*a;
document.getElementById("outputSquare").value=b;
}
Also. you have to put the code in <script> tag inside head. Not in dom load or jquery ready function. Check it out here: https://jsfiddle.net/q7oms4nh/
need to have var a = document.getElementById("inputSquare").value
EDIT: What nevermind said.

OnChange event handler not working

I'm using onchange event handler with an input element. I know it's simple, I just added an onchange attribute. But it's not at all working also not showing any kind of error in console.
<script type="text/javascript">
function select(a) {
console.log(a);
document.getElementById("demo").innerHTML = a;
}
</script>
<p id="demo"></p>
<input type="checkbox" onchange="select('XYZ')">
select is a reserved word in JavaScript (sort of).
<script type="text/javascript">
function _select(a) {
document.getElementById("demo").innerHTML = a;
}
</script>
<p id="demo"></p>
<input type="checkbox" onchange="_select('XYZ')">
Note that, as the link above states, select isn't technically a reserved word (in JavaScript). It can be used in general for variable names and functions. But, browser implementations do refuse to bind DOM events directly to functions that share DOM property names. And, I'm not yet sure where this restriction or conflict is explicitly named in the specs ... or if it's just an unhappy accident.
Javascript has a list of reserved keywords which cannot be used as function names or variable names.
For a complete list, check this link:
http://www.w3schools.com/js/js_reserved.asp
<script type="text/javascript">
function select1(a) {
console.log(a);
document.getElementById("demo").innerHTML = a;
}
</script>
<input type="checkbox" onchange="select1('XYZ')" name="xyz" value="xyz">
<p id="demo"></p>
you should change your function name becouse there is collision occurs that's why it's not working try above

Why won't JavaScript run?

I was making an HTML code editor, I tested all of the HTML tags I know and they all work, except for script tags.
When I type <script>something</script> into the text area and click a button, the script doesn't execute.
Please help! Here is the code:
<span id="finishedProduct">
<p>When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!</p>
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea></br>
<button type="button">Run Code!</button>
</form>
<script>
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here is the working code:
<span id="finishedProduct">When you enter code, your finished product will be here! Don't worry, if you make a mistake you can fix it later!
</span>
<form name="userCode">
<textarea name="userCode" cols="90" rows="20" placeholder="Type your code here"></textarea>
<br/>
<button type="button" onClick="makeCode()">Run Code!</button>
</form>
<script type="text/javascript">
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
</script>
Here's a link to the JSFiddle: http://jsfiddle.net/Q2qLF/. I've removed some broken HTML, such as; a button shouldn't be contained in a anchor tag, I've added a 'onclick' in your button that will call the 'makeCode()' function and I've added the 'type="text/javascript"' into your script tag as this maximises compatibility.
Please let me know if you need any more help
I've updated my JSFiddle http://jsfiddle.net/Xanco/Q2qLF/1/
Now there are 2 textareas, one for the HTML and one for the Javascript. i've also created a new function called 'makejs', this takes the value of the Javascript textarea and runs it through a 'eval' - this executes the Javascript passed to it.
I've put the answer in a Fiddle here: http://jsfiddle.net/joshnicholson/P8eh9/
I'm not sure why you're wrapping the button element inside an anchor, but I would do it a slightly different way.
Here is the revised javascript:
var myButton = document.getElementById("btnRunCode");
myButton.addEventListener("click", makeCode);
function makeCode() {
var userCode=document.forms["userCode"]["userCode"].value;
document.getElementById('finishedProduct').innerHTML = userCode;
}
I added an id of "btnRunCode" to your button element, just to make things easier for me. See the Fiddle.

Simple Javascript question

When I click on the button, the first time, everything works fine, but the second time, nothing happens. Why is that?
<form name="alert"><input type="text" name="hour"><input type="text" name="min"><input type="button" value="ok" onclick="budilnik(this.form)">
<script type="text/javascript">
function budilnik(form)
{
budilnik=1;
min=form.min.value;
hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
Learn to use Firebug. It'll help you immensely in the future.
budilnik=1;
This may sound crazy, but this is redefining the function budilnik to an integer, which breaks your form's onlick. If you preface this statement with keyword var, you will shadow the function but not overwrite it. When you do not specify the var keyword, variables are assumed to be global scope, which can cause issues (like this).
I used firebug to see that on the second click, "budilnik is not defined." If you had used this tool, you could have probably debugged this issue yourself.
The variable budilnik is shadowing the function budilnik. Change the name of the variable, and your function should work right every time.
In more detail:
First, JavaScript sees budilink defined as a function. When budilnik is executed, the value of budilnik is overwritten with the integer 1. So the next time JavaScript is told to execute budilink, it tries to execute 1, instead of the function that was there before.
Put the var keyword before your variable name.
I've tested the following code and it just works:
<form name="alert">
<input type="text" name="hour">
<input type="text" name="min">
<input type="button" value="ok" onclick="budilnik(this.form);">
<script type="text/javascript">
function budilnik(form)
{
var budilnik=1;
var min=form.min.value;
var hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
Change budilnik=1; to i_budilnik=1 or some other variable name .. by specifying budilnik=1; you are changing the definition from a function to a int val.
Alternatively you could try var budilnik=1; but not sure if that solves.

Is it possible to duplicate the native behavior of JavaScript's prompt()?

I'm rolling my own version of prompt() for aesthetic purposes; it's come along quite nicely as far as visuals go, but I have run into a slight hitch: the native version of the function causes code execution to cease completely until the prompt has been dealt with.
This is positively lovely and it's why the below works the way it does:
<script>
var c = prompt('Name?', '');
alert(c); // displays whatever the user entered
</script>
With my method, however, things do not go as smoothly. I am using a dialog, an input box, and an OK button to gather the data from the user; to my knowledge, data collection works perfectly; that is, I know for sure that after the user presses the OK button, I have access to the data they just put into the prompt.
I cannot, however, find a way to get my version to work as the native one does. My question, then, is this: is it at all possible to tell JavaScript to halt executing until you've told it to resume?
Thanks in advance for any and all assistance.
No, it is not possible to duplicate this behavior. The way to achieve the same effect is to use a callback in your code, so you can do something like:
myPrompt('Hello, mate, whats yer name?', function(answer) {
alert(answer);
});
EDIT: Based on your code, why not do this?
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(prompt, callback) {
$('prompt').style.display = '';
$('q').value = '';
$('ok').onclick = function() {
callback($('q').value);
}
}
_prompt('Name?', function(answer) {
alert(answer);
});
</script>
</body>
If you change alert(answer); to say... gAnswer = answer; (notice no var declaration) you would be creating a global variable named gAnswer that you could access anywhere else in the javascript code, assuming the prompt was already answered. If you're concerned of global variables polluting your space you could wrap it all in a closure, but it should be fine otherwise.
#Paolo:
This is the code I am currently working with:
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(q, e)
{
$('prompt').style.display = '';
$('q').value = '';
$('ok').setAttribute('onclick', e + ' $("prompt").style.display = "none";');
}
var c; _prompt('Name?', 'c = $("q").value;');
alert(c);
</script>
</body>
Now, as would be expected, that alert() fires as soon as the page is loaded, which is most definitely not what I want; ideally, I'd like for the rest of the code to wait for the prompt to get handled, but I'm strongly doubting this is possible outside of the native implementation. Reckon I'll just have to settle for designing my algorithm so that the prompt gets used immediately?

Categories