I am following a JavaScript tutorial on the W3Schools website and I have the following code:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<script type="text/javascript">
function confirmShow
{
var r = confirm("Press one...")
if (r == true)
{
alert("Button pressed == OK")
}
if (r == false)
{
alert("Button pressed == Cancel")
}
}
</script>
<input type="button" onclick="confirmShow()" value="Show Confirm Box" />
</body>
</html>
and whenever I preview it in Coda or in Safari the alert never shows up.
Thanks in advance!
"function confirmShow" => "function confirmShow()"
Firebug is good for js debugging, try it. Safari has options too, AFAIK.
function confirmShow
{
function confirmShow()
{
?
I don't know if this is your problem, but your button is outside the <body> tag. That might cause you some trouble...
Also one would usually put a script like this in the <head> element. Just FYI.
1) w3schools is filled with errors and omissions. Better tutorials can be found at howtocreate.co.uk
2) You have no DOCTYPE declaration, and you're using XHTML syntax.
2.1) IE doesn't support true, see webdevout.net/articles/beware-of-xhtml for more information
3) You need to encapsulate the within a element as well as another block-level element as per the specification
See below for a proper HTML5 document. Notice the location and syntax
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<script>
function confirmBox() {
var ret = confirm('Some Text');
/*
Note the 3 equal signs. This is a strict comparison operator, to check both the 'value' as well as the type. see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators for more
*/
if(ret === true) {
alert('Alert box for "Okay" value');
}
else if(ret === false) {
alert('Alert box for "Cancel" value');
}
}
window.onload = function() {
// Execute the confirmBox function once the 'button' is pressed.
document.getElementById('confirmBox').onclick = confirmBox;
}
</script>
</head>
<body>
<form>
<p>
<input type="button" id='confirmBox' value="Show Confirm Box">
</p>
</form>
</body>
</html>
Related
I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?
if(document.getElementById("btn").clicked == true){
//some code here
console.log("working");
}
<button id=""btn>ClickEvent</button>
Do not use the if. if statement is executed on page load.
Instead, use Onclick() for example :
var data = "";
function clickBtn() {
if(data != "")
document.getElementById("result").innerHTML = "Hello World !";
else
getData();
}
function getData() {
data = "Hello World !";
}
<button onclick="clickBtn()">Click me</button>
<p id="result"></p>
Good question, lets use the an HTML file that references a JavaScript.
So the first file lets call it webpage.html
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="save" onclick="save()"></input>
<input type="button" value="display" onclick="print()"></input>
<div id="area"></div>
</body>
</html>
And the second file script.js
function save()
{
StringTest="Hello world";
}
function print()
{
document.getElementById("area").innerHTML=StringTest;
}
The approach might be a little different but this is recommended as you would more control over the elements in the script.
For example:
<input type="button" will tell the script that it is a form input of the type button whose click will call the function print() in the JavaScript
document.getElementById("area")captures the elements that we define from the Document Object Model(DOM)
This has been asked 100x before but after reading a lot of those posts I'm still not sure what I'm doing wrong. The script is only executed when you press the button (so the textbox should exist in the DOM by the time the code is executed), Visual Studio even lets me autocomplete the getElementByID argument to inputField. Yet somehow it doesn't get the element and 'null' is printed on my screen.
My code is:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!-- input field + button, and an empty value field -->
<input type="text" id="inputField" value="" />
<input type="button" onclick="printType()" />
</body>
<script>
function printType() {
console.log(document.getElementById(inputField).value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById(inputField)
)
); //also try get_type to see if it exists, we're expecting a string
}
//stole this function from a stackoverflow post
function get_type(thing) {
if (thing === null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
</script>
</html>
You're missing quotes:
document.getElementById(inputField);
Should be:
document.getElementById('inputField');
Based on #Schlaus answer, I created a jsfiddle with correct answer.
function printType() {
console.log(document.getElementById('inputField').value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById('inputField')
)
); //also try get_type to see if it exists, we're expecting a string
}
For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>
When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here
So I have been working on this for a couple of days and as a newbie, I think the answer will really help my understanding of JavaScript.
I have a page that contains a form -- when a user submits the form a new window opens with form variables embedded within text in new window. It works fine.
The problem I am having is I want to add an alert to the new window if the user onClick types in NY || New York || NJ || New Jersey. I tested my if function (I left out the else after doing some research since else is really do nothing.
The way I want it to work is if someone types one of those four variables, a new window opens with the alert. If they don't type in one of those variables, only the new window opens.
I prepared a truncated test code which I'll put below. I know there are better ways to do this then the code I have written, and I bet there are probably easier ways with libraries, jquery, etc., but I would love for someone to show me how to add the askForHelp function so it will open the alert in the new window with code I have written. Again, that's b/c this is my knowledge base at this point, and it would help me see how to really write a statement. Thanks in advance for any help offered.
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if (volunteer == "New York" || "NY" || "New Jersey" || "NJ") {
allInfo.document.open.alert("test test test"); //Do I put the statement here?
} // else do nothing
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp()" ></p> <!-- Should askForHelp() be here? -->
</form>
</body>
</html>
You have 3 problems in your code:
1- You are trying to get a value for element with id=country and you don't have any element with id=country
allInfo.document.write('<p>' + document.getElementById ('country').value);
2- alert() function is attached to the window object not to the document object. So when you want to call the alert in the new window, you should call it like this:
allInfo.alert("blah blah");
3- The If condition in your code will always return true it should modified and be like this:
if((volunteer == "New York") || (volunteer =="NY") || (volunteer =="New Jersey") || (volunteer =="NJ"))
I have made the above modifications in this jsFiddle. Please check it.
Since I'm using JSFiddle, it won't let me put document.write but you can still how it works.. Check out this Fiddle, below are the changes that I made..
HTML:
<p><input type="button" id="submit-btn" value="Submit Information" ></p>
JS:
function newWindow() {
alert("New Window");
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if (volunteer == "New York" || volunteer == "NY" || volunteer == "New Jersey" || volunteer == "NJ") {
alert("test test test");
}
}
document.getElementById('submit-btn').addEventListener("click", function(){
newWindow();
askForHelp();
});
I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior here
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that.
Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
$('#password').bind('input', function(){ /* your code */});
I've had the same problem.
Apparently, there is password manager debugging available
https://wiki.mozilla.org/Firefox:Password_Manager_Debugging
So I've found that for me DOMAutoComplete event got triggered and
I've managed to attach it sucessfuly to a field via jQuery's bind like
$('#email').bind('DOMAutoComplete',function() { ...
If it makes you feel better, it is a known bug
Proposed workaround: (Not mine, from here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
Another Suggested work around. This time using polling, you can work it in exactly
the same way, checking for "changes" to your field. Tweak the poll value (default to
375ms for your own taste).
I've used jQuery and a jquery plugin someone wrote:
https://github.com/cowboy/jquery-dotimeout/
Git Hub Src: https://raw.github.com/cowboy/jquery-dotimeout/master/jquery.ba-dotimeout.js
<html>
<head>
<meta charset="utf-8">
<title>onChange() for Firefox / IE autofil get-around</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/~dsloan/js/ba-dotimeout.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var val;
var count=0; // used to illustrate the "poll count"
// when focusing on the element and typing
// (vs not focused)
// set a focus function to poll the input
$("#myname").focus(function() {
// start polling
$.doTimeout('checkname', 375, function() {
++count;
// no changes, just exit this poll
if($("#myname").val() == val) {
return true;
// store the value
} else {
val = $("#myname").val();
}
var str;
// do stuff here with your field....
if($(document.activeElement) &&
($(document.activeElement).attr('id') ==
$("#myname").attr('id'))) {
var len = $("#myname").val().length;
if(len == 0) {
str = 'Timer called, length 0...';
} else if(len < 2) {
str = 'Timer called, length < 2...';
} else {
str = 'Timer called, valid!';
}
}
// show some debugging...
$("#foo span").html(str+' (count: '+count+'): '+
$(document.activeElement).attr('id')+
', val: '+$("#myname").val());
return true;
});
});
// set a blur function to remove the poll
$("#myname").blur(function() {
$.doTimeout('checkname');
});
});
</script>
</head>
<body>
<form action="#" method=post>
Name: <input type="text" name="name" value="" id="myname" />
Scooby: <input name="scooby" value="" id="scooby" />
<input type="submit" value="Press Me!" />
</form>
<div id="foo"><span></span></div>
</body>
</html>
A possibly alternative: could you simply use a timer to tell when the value of the text box changes?
You're going to have to blur the input field and reset the focus to it. That's going to require a little trickeration though.