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();
});
Related
I wrote a very quick javascript function to validate a very small form on an internal form used in our office. However, someoner today told me that it doesnt work in Edge, the code does not ever enable the submit button.
I console.log out the var values every time the function runs, and in edge, the vars are forever undefined. It seems like Edge does not respect "document.forms["abc"]["xyz"].value", but I cannot find any documentation or notes to support that.
I should clarify, I am not a javascript pro, I uyse it very sparingly, and in simple ways to get smal tasks done like this, so please dont judge my code too hard, haha.
Console Log:
q1=undefined
q2=undefined
q3=undefined
q4=undefined
My code is below, its pretty simple, nothing fancy..
function fieldcheck(){
var q1=document.forms["datacollect1"]["q1overall"].value;
var q2=document.forms["datacollect1"]["q2understand"].value;
var q3=document.forms["datacollect1"]["q3time"].value;
var q4=document.forms["datacollect1"]["q4recommend"].value;
console.log("q1="+q1+"\n"+"q2="+q2+"\n"+"q3="+q3+"\n"+"q4="+q4);
document.getElementById("datacollectsubmit1").disabled = true;
if (q1 && q2 && q3 && q4){
console.log("q1234 set");
document.getElementById("datacollectsubmit1").disabled = false;
}
}
I call the above on every click with:
document.onclick = function(){
fieldcheck();
}
Anyone have any clue as to why Edge is playing games? Or what I can substiture for document.forms.value that will work across other browsers and Edge too? Thanks.
Your above code is working in MS Edge. Possible that some other code caused this issue. I suggest you to take the code below and run it in MS Edge.
Code:
<!doctype html>
<head>
<script>
function fieldcheck(){
var q1=document.forms["datacollect1"]["q1overall"].value;
var q2=document.forms["datacollect1"]["q2understand"].value;
var q3=document.forms["datacollect1"]["q3time"].value;
var q4=document.forms["datacollect1"]["q4recommend"].value;
console.log("q1="+q1+"\n"+"q2="+q2+"\n"+"q3="+q3+"\n"+"q4="+q4);
document.getElementById("datacollectsubmit1").disabled = true;
if (q1 && q2 && q3 && q4){
console.log("q1234 set");
document.getElementById("datacollectsubmit1").disabled = false;
}
}
document.onclick = function(){
fieldcheck();
}
</script>
</head>
<body>
<form name="datacollect1" onsubmit="return fieldcheck()" method="post">
Name: <input type="text" name="q1overall"><br>
Name1: <input type="text" name="q2understand"><br>
Name2: <input type="text" name="q3time"><br>
Name3: <input type="text" name="q4recommend"><br><br>
<input type="submit" id="datacollectsubmit1" value="Submit">
</form>
</body>
</html>
Output in MS Edge browser:
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 is the code I used. It takes the first name and the surname from the user and then uses them in the MyChecker function where it matches up the names used to create different alerts. I can't get the MyChecker function to link to the values inputted by the user?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<p>What's your name?</p>
<form action="action.php"> //This form gets the input from the user
First Name
<br><input type="text" name="FirstName" value="" id="txt1"><br>
Second Name
<br><input type="text" name="SecondName" value="" id="txt2"><br>
<button onclick="myFunction()">Submit</button>
</form>
<script type="text/javascript">
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
var x= FirstName.localeCompare("Donald");
var y= SecondName.localeCompare("Trump");
MyChecker();
function MyChecker()
{
if(x==0&&y==0)
{
alert("I love the poorly educated");
}
var a= FirstName.localeCompare("Edward");
var b= SecondName.localeCompare("Snowden");
if(a==0 && b==0)
{
var ask=prompt("Would you mind collecting your cake from our office in Pennsylvania?","Choose between yes or no");
var cmp=ask.localeCompare("yes");
if(cmp==0)
{
alert("We'll even reimburse your plane tickets!");
}
else
{
alert("Perhaps next time...");
}
}
if(a!=0 && b !=0 && x !=0 && y!=0)
{
alert("Carry on...");
}
}
</script>
</body>
</html>
I touched up your indentation and hopefully it helps to expose the issue. When you submit the form, you will call myFunction, which I've copied here for clarity:
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
... and that's it. These values aren't even saved.
You probably mean to have myFunction call MyChecker, so that your logic will be executed each time the form is submitted.
You might also consider having MyChecker take in the FirstName and SecondName as parameters, since myFunction is already reading values from the form.
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>
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.