Cant Seem To use var twice in function - javascript

Okay heres my problem.. i am trying to make a button onclick in the function i have defined a variable but... i want to be able to click the button to a prompt type in a website in the prompt use window.location to go to which ever site... but when the user clicks ESC or cancel in a prompt its equal to (null or false). But when i click the cancel button it goes to null as if it was a href..
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = done;
}
if (done === null) {
window.location = "java_doc.htm";
}
<button onclick="goToSite()"></button>

You gotta make your conditional statement run before you change window.location, otherwise your address bar will point to null. Also, your function's closing brackets are in the wrong place, and you are closing your function before it actually does its thing.
function goToSite(){
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
if(done === null){
window.location = "java_doc.htm";
} else {
window.location = done;
}
}

You can do the following:
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = (done === null) ? "java_doc.htm" : done;
}
To take it one step further you can validate if the user actually entered a valid url.
function validUrl(textval) {
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*#)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function goToSite() {
var done = prompt("Please Enter a Website You'd like to go to - Or click \"Cancel\" to go back to the main page.");
window.location = (done === null || !validUrl(done)) ? "java_doc.htm" : done;
}
This makes sure that only if user entered a valid url, they will be taken to that url. Otherwise they will be redirected to your default page.

Related

Trying to get AJAX field to update with returned value (But have to click away before it updates)

Image of form that uses AJAX & JS
I've currently got a maintainer that uses AJAX so when I type a number into the "Order No" field the "Calc" field then gets updated with the "Account" associated with the Order No. It all works however the "Calc" field doesn't fill with the account number until a click away from the Order No field has been done which means that if you were to press the enter key after typing the number the calc is still blank when the checks were made to see if the account and calc numbers are the same.. If you were to type the number then click the "Accept" button the update is then done so the checks then work as expected. So I was wondering if there is a way so that this field could get updated without an extra click.
One solution I came up with was by doing the checks such as account==calc and calc != "" twice so it would run a function where the check would always say that the calc field is blank (as it hasn't updated at this point) which would return an alert saying "Blank" then after returning the alert it would run another function which is exactly the same to do the check again and this time it would work as expected but once the alert is taken out its as if it hasn't got that moments wait which allows for the Calc field to be updated in time.
Its hard for me to post all the code as I use a system that does all the AJAX behind the scenes for you but let me try explain how the AJAX works. Whatever you put in the Order No field will be sent to an external retrieval application that would check to see what account number is associated with the order no and then return it to the Calc field. If then the account and the calc field numbers match submit the form else say its an incorrect order number for that specific customer.
Here are the two JavaScript functions:
function testerRun() {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
//alert("Blank First Step!");
finalStep();
}
}
function finalStep() {
if (document.getElementById("CALCULA001").value == "") {
alert("Customers Account Details Need Amending..");
return false;
} else {
var abc = ('${row.CUSN760?html}').toString();
var def = document.getElementById("CALCULA001").value;
if (abc == def && abc != "") {
//alert("Order Number & Account Number Match!");
document.getElementById('FORM_M07052').submit();
return true;
} else if (document.getElementById('ORDN760').value == "") {
document.getElementById('FORM_M07052').submit();
return true;
} else {
alert("Order Number & Account Number Do Not Match!");
return false;
}
}
}​
And here is where the script is called:
<input class="btn btn-primary accept" id="btnaccept" name="btn_accept" onclick="testerRun();return false" type="submit" value="Accept" />
#Shreyas Sorry there is no blur or change as im using a system called MRC and so they use behind the scenes AJAX scripts to handle thigns like this what I don't have access too so I need some sort of work around. Its only an issue when the user clicks enter in the order no field after entering the order number without doing anything else on the form as it doesn't update until the order number is deselected.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
testerRun();
}
}
Function call not working though doesn't seem to do anything just sits there after blur.
Add a keypress handler on the Order No field, which listens for the Enter key, and submits the form when Enter is pressed.
document.getElementById('ORDN760').onkeydown = function(event){
if (event.which == 13 || event.keyCode == 13) {
document.getElementById('ORDN760').blur();
return false;
}
}

preventDefault() overruled by window.location

I have process in my website which contains a few steps. To navigate I have "previous" and "next" buttons. These buttons are <a> elements with an href attribute (to visit the previous and next step).
The next button works as a door to the next step, but also to validate some fields in the current step, before it continues.
So this is what happens when clicking the next button:
The href value got saved in a variable $url.
preventDefault() prevents the link from opening the URL.
There are some validation checks done.
If they return "true", the $url will be loaded in window.location.
For some steps I need to do another check to the user with a confirm box. But here comes the problem:
Problem:
When the confirm() returns "false", the user should not go to the next page. But the window.location of function 1 "overrules" the preventDefault() of function 2 now.
1. Default next button function:
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
});
2. Confirm box function:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == false) {
e.preventDefault();
}
});
I would do something like that. If you have any question for the code please ask!
fiddle
// These can be changed for each step if you want or not a confirmation
var needs_confirm = true;
var cb_message = 'Have you specified the dimensions in millimeters?';
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if (needs_confirm === true) {
if (confirm_box(cb_message) === true) {
redirect_window(url);
}
} else {
redirect_window(url);
}
});
function confirm_box(cb_message) {
if (confirm(cb_message) === true) {
return true;
} else {
return false;
}
}
function redirect_window(url) {
if (wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="next_link">link
</div>
Where do you called the dimension-check?
e.preventDefault() only cancel the default action of a button which is submit the form. Regardless of e.preventDefault windows.location will always redirect you.
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
//If dimension isnot prompt{
//windows.location
//}else call dimension prompt
}
});
You can put the windows.location like this:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == true) {
window.location = url;
}
});

How do I write a JS function to disable the function under certain conditions

I'm writing a simple game in JS. It's essentially a game of chance. You press a button (which runs a function) and if it doesn't return number 9 then it shows a picture, you get a point and keep going. If it does return a 9 you see a losing picture and you loose. The game waits two seconds, (so you can actually see the losing image) and then throws an alert message telling you your high score and then refreshes the page.
The problem is between the two seconds of you loosing and receiving the alert message you can still click and receive points. Is there a way to disable the function form being called again? I am looking for a way to do this.
var didIGetAPoint = function() {
if(num != losing number) {
show pic, get a point and keep going
}
else { show losing pic, disable this function from running again, pause, then alert box.}
}
Create a boolean variable to set whether the game is over or not.
Here is my example. JSFIDDLE
HTML
<button id="pointbutton" onclick="clickforpointsandlose()">Click me to earn points and Lose!</button>
JS
var points = 0;
var isaLoser = false;
function clickforpointsandlose(){
if(!isaLoser) {
//show pic, get a point and keep going
points+=1;
console.log("total points "+ points);
}
else {
console.log("You can't earn points because you already lost.");
//show losing pic, disable this function from running again, pause, then alert box.}
}
}
console.log("You are losing in 2 seconds");
loserhaha = setTimeout(function(){
alert("You Lose!");
isaLoser = true;
}, 2000);
The simplest way of doing it would be to disable your button ( remove the onclick handler & set the button disabled attribute).
you can do something like this.
var gameover = false;
var didIGetAPoint = function() {
if(num != losing number) {
if (gameover === true) {return false;}
show pic, get a point and keep going
}
else { show losing pic, disable this function from running again, pause, then alert box.
gameover = true;
}
}

jquery code working but not the first time

I'm trying to build a small login system using jquery (since it is for testing purposes only and the user and password won't change) So i made a form and when you click the button i test whether the details are correct. if so you will get send to the next page. If not i give an alert.
It's working but i have something weird. The first time you visit the site and fill in the details it does nothing. The second time (after submitting) it works like it should.
Does someone know why?
Here is the code:
function controllogin() {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username=="leerkrachten" && password=="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username=="leerling" && password=="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
};
function goToUrl() {
alert("zoeken naar pagina");
window.location = 'leerkrachten/vakken.html';
};
Instead of onclick="controllogin();" try something like this:
$('document').ready(function() {
$('#submit').click(function(event) {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username==="leerkrachten" && password==="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username==="leerling" && password==="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
});
});
Also use === instead of == as operators to compare the strings, it prevents you from some weird results when comparing different types. Maybe that's why it doesn't work the first time, but does the second time. Otherwise I don't know why this happens.
But actually I'd have to say: NEVER do client-side login validation and NEVER do login validation with an unencrypted password (not even server-side)!

How redirect cancel function in Javascript

I'm not a programmer. I don't want to protect with a strong secure code my page. I just need one option I'm missing in my code and can't figure out how to add it.
<script language="Javascript">
<!--
var password = "lala"
var x = prompt("","")
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
//-->
</script>
As you can see it's so dump but I need it. When I press Cancel button instead of writing true or false text, website still opens. I want to include in this script cancel button function (control it, you know) whitch would redirect to another website if press on it (as it is with true or false functions). I don't want to creat a special button or an input for it.
Update: I would like to include this script in a page which i am redirecting to. Could anyone tell me:
1. How can i modify this script to make it work only once?
2. Is it anything to do with browser's cookies?
p.s. Done :)
If the user presses cancel, prompt will return null. So do like this:
if(x == null) // Cancel
{
alert('Cancel');
}
else if (x.toLowerCase() == password) { // Correct password
location = "http://google.com";
}
else { // Wrong password
alert("Fail")
location = "http://facebook.com"
}
However, I'm not sure if all browsers will return null when the user presses cancel. (I have tested in Opera)
Try
var x = prompt("","");
if( x == null || x == '')
return;
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
To redirect your browser to a URL use following snippet in your Javascript:
top.location.href = "http://google.com";

Categories