Javascript function fails to perform task in Google Chrome - javascript

I've been researching this problem for a while, and given the immense amount of issues Google Chrome seems to have with Javascript, I've been having trouble finding anyone with this same issue.
The problem is this: when the anchor calls a new function which replaces the contents of a div, it shows the proper result for a moment before reverting to the default contents of the div prior to any changes by Javascript.
Here's the script:
function prologueThree() {
document.getElementById('content').innerHTML = document.getElementById('prologue3').innerHTML;
}
function prologueFour() {
userName = document.getElementById('yourname').value;
if(userName.length === 0) {
alert("Erm... are you sure that\'s your name?");
prologueThree();
} else {
document.getElementById('content').innerHTML = '<center> \
<img src="http://pokemonroleplay.thedevhome.net/images/Gameboy/characters/red.png"><br> \
Right, so your name is ' + userName + '! \
<br><br> \
<a onclick="prologueFive()"><button>>>Continue>></button></a></center>';
}
}
This is only a snippet of the script, but the entire thing works fine in Firefox and for the first three prologue functions it works fine in Chrome. It's only when it tries to run prologueFour that it freaks out and go back. I've also tried the Chrome developer console, but it never registers an error.
Thank you in advance for your help.

I went to your site
and I noticed you are binding an onclick to a submit button in your form without preventing the default behavior from executing, the default behavior being a form submission which refreshes the page and thus makes you lose your place and go back to the beginning. Use a plain old button or anchor tag like you do for your previous prologues. If you insist on using a submit for whatever reason, prevent the default behavior like so:
function prologueFour(e) {
typeof e.preventDefault === 'function'
? e.preventDefault()
: e.returnValue = false;
// now rest of code can continue without page refresh
}

I don't know if there are other issues, but >>Continue>> isn't exactly standards-compliant html, which could be causing problems. You should use > instead.

Related

Javascript and php execution priority in different browsers

I have a simple JS statement, which kind of "protects" me from using special characters in a login form on my website:
$("#login_button").click(function(){
formChecker();
});
function formChecker() {
var checkLogin = document.forms["loginForm"]["username"].value;
if ((checkLogin.indexOf("!") > -1) || (checkLogin.indexOf("#") > -1) || (checkLogin.indexOf("#") > -1)) {
alert("Special characters not allowed! Please use A-Z and numbers.");
document.location = "http://mywebsite.com/";
}
}
It works fine in Chrome. Whenever someone is using one of these characters, he is getting redirected instantly, so the php login script is not executed.
The problem occures when I am using it in Internet Explorer. It actually redirects my page but the php script is executed anyway. I have also tried window.location but it doesnt work at all in IE. What is the problem with this browser? Is the scipt priority different in different browsers?
What I mean is that on IE, even though the user is redirected, when he comes back to the website, he is logged in, but he shouldnt be. The chrome browser does not log in the user because page is redirected and it is how it should work.
This is not how to do form validation. There is no guarantee that click will be called on the button (eg the form might be submitted by pressing Enter); you aren't preventing the form from being submitted by doing a redirect (it's a race condition which might happen first); and also alert-and-redirect is pretty user-hostile.
You should be picking up the submit event on the form itself, and cancelling the event if you don't want the form to submit. For example add a div with id="formErrorMessage" to the page and then:
var goodUsernamePattern = /^[a-zA-Z0-9_-]+$/;
$('#loginForm').on('submit', function(event) {
if (!goodUsernamePattern.test(this.username.value)) {
event.preventDefault();
$('#formErrorMessage').text('Please enter a good username blah');
}
});

Jquery mobile function not working == page refresh?

Ok this thing is driving me crazy. I have a simple project in which I use this mobile bootstrap theme and this text-to-speech library
Whenever there's an error in my function, the page just refreshes itself. In this way I can never read any output from the console.
Here's my code:
<script>
$(document).ready(function() {
$('#input-submit').click(function() {
var text = $('#input-box').val();
console.log(text);
for (var i = 0;i < text.length; i++){
alert('test');
meSpeak.speak(text.charAt(i));
}
});
});
</script>
I want my app to spell out loud whatever the user fills in. The function works correctly until the meSpeak.speak(text.charAt(i)); line. When I type in a 3 character word I get 3 alerts, and then the page just refreshes itself.
Why does it refresh when there's something not working? I want to read the output from the console without using alerts. Also, does anyone know why I can't use meSpeak.speak(text.charAt(i)); like this?
You're not preventing the submit button from "submitting" the page, and as you've most likely set no destination, it's submitting to the same location, causing a page refresh.
Preventing the click event can be done in jQuery by returning false at the end of the function
$('#input-submit').click(function () {
/* etc */
return false;
});
Demo to play with

asp.net javascript .click() event not firing on server

I have the following code which is working fine on the development machine. But, when I deploy it to IIS, the .click() does not fire.
I have drop down box, when a status is selected, I add the following code to open up a RadWindow
if (ddlStatusID.SelectedValue.ToString() == "2")
btnUpdateStatus.Attributes.Add("onclick", "return OpenWindow2('" +
ResolveUrl("~/Request/AddBillableTime.aspx? RequestId=" + RequestId.ToString()) +
"','650','320');");
else
btnUpdateStatus.Attributes.Add("onclick", "");
In the popup page, when the user clicks on a button I add do the following
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow",
"ClosePopup();", true);
This is the ClosePopup javascript.
function ClosePopup() {
//debugger;
alert('This is before closing the window');
var oWindow = GetRadWindow();
oWindow.argument = null;
oWindow.close();
alert('This is after closing the window');
oWindow.BrowserWindow.ButtonClick();
}
In the main window, I have following javascript, which is invoked in the last line of the above javascript.
function ButtonClick() {
//debugger;
alert('This is before button click!');
var btnUpdateStatus =
document.getElementById('ctl00_ContentPlaceHolder1_btnUpdateStatus');
alert('This is getting the button!');
btnUpdateStatus.setAttribute("onclick", "");
alert('This is setting the button!');
btnUpdateStatus.click();
alert('This is after clicking the button!');
}
I have used the alerts to check how far the javascript function is executed.
The entire functionality is working fine when I run it using Visual Studio and also when I host it in my local IIS server. But, when I deploy it to the server, the click() event stops firing.
Please let me know if there is anything wrong in the code.
I didn't had time to look into this issue for some as I was assigned to a new task. But had to fix it once I was back in the same task. I got some help from a friend of mine to fix the issue. I had to change the current logic a bit and have explained the solution below.
I changed the ButtonClick function as below to create a manual post back to the page using the __doPostBack function.
function ButtonClick() {
__doPostBack('btnUpdatePage', '');
return;
}
I handled the post back from the Page_Load method of the page.
if (Request["__EVENTTARGET"] == "btnUpdatePage")
{
UpdateStatus();
}
If the post back event target matches the assigned event target from the __doPostBack method, then I called a method to update the status.
This way I could avoid the issue. But I do not know why the event was not fired using the old ButtonClick function.
If the code works fine on your PC, the only thing that looks fishy to me are these 2 lines:
1. document.getElementById('ctl00_ContentPlaceHolder1_btnUpdateStatus');
2. btnUpdateStatus.setAttribute("onclick", "");
For the first line , you should be doing this, instead:
document.getElementById('<%=btnUpdateStatus.ClientID%>');
And for the second line, it seems that you are setting the onclick handler to "" which basically shouldn't do anything.
It may not be the problem at all. The best thing to do is debug it with Firebug, putting a breakpoint in the appropriate Javascript functions that are being called.

Could someone point out the error in my jQuery?

I'm making a script to open all links on a page when I click a button in my toolbar. What exactly is wrong with the following code?
function performCommand(event) {
if (event.command == "open-tests") {
$('a').each(function(index, elem) {
window.open($(elem).attr('href'));
});
}
}
As far as getting to the function, it does this fine, as if I comment out the if statement and put in a simple alert, it will work as expected. However the above code does not work.
There is no standard command property of the event object provided by jQuery.
Why do you think there is one?
Did you disable your PopUp Manager or are you using any other kind of adblocker / secure plugin?
Despite that Safari refuses to window.open when called in a callback
more to read:
http://jensarps.de/2009/08/21/safari-and-window-open/

Javascript, controlling an onbeforeunload tag

I'm trying to set up a onbeforeunload tag to stop a user from leaving specific pages if and only if they have unsaved content, and only on specific pages (we're using a single master page). I quickly discovered that having a return ##anything## in the onbeforeunload tag would always trigger a javascript confirm, and puts ##anything## inside the pop-up. Obviously, this is now expected behavior, but it does take away my idea of using my own confirm box that could be controlled with an if statement.
I tried this, and it didn't work:
<body class="yui-skin-sam" onbeforeunload="document.onFormClose();">
<script>
document.onFormClose = function () {
if (document.getElementById('DirtyFlag').value == "true") {
document.getElementById('DirtyFlag').value == "false";
return 'You will lose all changes made since your last save';
}
}
</script>
where DirtyFlag is a hidden field that turns true if any unsaved changes exist. I'd hoped that putting the return inside the function would do the trick, but no such luck.
So my question is, is there a way to use the onbeforeunload tag with a return built in that will bypass it pending the value of that field?
Alternatively, (though this would be less ideal) I suppose I could add or remove the onbeforeunload tag dynamically, in all the places I set or reset the getElementById tag. Unfortunately, I don't know how to do that either.
Oh, and I'm restricted completely from using jQuery or any other javascript library.
Not sure if this is as designed, but if you return null from the event handler, you might get the results you want:
window.onbeforeunload = function() {
var el = document.getElementById("dirtyFlag");
if (el.value === "true") {
return 'You will lose all changes made since your last save';
}
else {
return null;
}
};
The following works in FF: http://jsfiddle.net/andrewwhitaker/chZJ8/. Try changing the hidden inputs value to "true" and you should start getting the confirmation dialog. However, I cannot get it to work in Chrome and I'm unable to test in IE. It would be great if someone could confirm this works in either of those browsers.
Edit: Adding another example that's easier to use and works in Chrome (the iFrame in JSFiddle was causing issues). Check out the example here: http://andrewawhitaker.com/examples/onbeforeunload_test.html. Type 'true' in the input to see a confirmation. If 'true' is not the value of the input, no dialog is displayed. Works in FF and Chrome, still can't vouch for IE.
Update 2: A more reliable way of doing this is probably to add and remove the event listener when you set the value for dirtyFlag programmatically, just remove or add the event handler appropriately:
var isDirty = function() { ... };
if (/* form is dirty*/) {
window.onbeforeunload = isDirty;
}
else {
window.onbeforeunload = null;
}
You can't change the default behavior of onbeforeunload.
https://developer.mozilla.org/en/DOM/window.onbeforeunload
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx

Categories

Resources