Simple Javascript question - javascript

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.

Related

How to highlight Javascript missing brackets calling function

In the following HTML/Javascript snippet, I'm missing the function's brackets in the onclick statement (it should read: onclick="showMessage()").
How could I get the missing brackets highlighted
(a) in Notepad before I display the page.
(b) in my Browser JS console after I display the page?
If this is not possible besides inspection, is there another way I could identify this issue more easily?
<html>
<head>
<script>
function showMessage() {
document.getElementById("messageArea").innerHTML = "Hello World";
}
</script>
</head>
<body>
<input type="button" value="Show message" onclick="showMessage">
<div id="messageArea">---</div>
</body>
</html>
The problem is onclick takes any kind of javascript expression, function execution being one of them. For example:
<script>
var a = 10
</script>
<!--All are valid and don't throw any errors -->
<button onclick="a">Nothing happens</button>
<button onclick="a++">Increment</button>
<button onclick="alert(a)">Check value</button>
<button onclick="undefined">Surely Not?</button>
Executing functions like showMessage() is one of it's primary use. And technically it's not an error to have a showMessage without the () inside the onclick. showMesage is just function definition, If you were to type showMessage and press enter in your browser's console, it will simply return the function definition and won't throw any error. So IDEs don't underline it as an error because it's not an error.
I don't know of any tool that will look at html attributes for possible errors like this.
However, if you move all of your javascript code to a separate file, you can use a tool like eslint to check for common errors.
So in this case, instead of using the onclick attribute in your HTML, you'd use javascript to select the element and add an event listener.

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

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

getElementById Not Working Right

Ok, so I'm REALLY new to programming and javascript, but I'm having a problem with this little string of code. The thing that is bothering me about it, is that I have done things similar to this in other programs, but it's just not working right in this specific little part of this program. Here is basically what isn't working:
<html>
<script type="text/javascript">
function test()
{
var myTextField = document.getElementById('myText');
document.write (myTextField);
}
</script>
<form>
<input type="text" id="myText">
<input type="submit" value="submit" OnClick="test()">
</form>
</html>
When I do this, it returns [object HTMLInputElement] instead of the value of that text field. Thanks for any help cause I'm most of you know this. :P
getElementById returns the Object itself, which has many methods and properties as members.
You need to reference the value property, like this:
document.getElementById('myText').value;
That should work :)
Also, here's a general reference: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript
Try:
document.write (myTextField.value);
function test()
{
var myTextField = document.getElementById('myText').value;
alert(myTextField);
// or
console.log(myTextField);
}
You should not use document.write here, as you document is already loaded. Document.write will remove the page.

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