I am designin a shoutbox which is AJAX based.
http://businessgame.be/shoutbox.php
The script works perfectly in google chrome, but other browsers don't act like I expect.
To shout a new message, there is a form which owns a input text field. When pressing enter, the form is being submitted, so I have omitted a submit button since pressing enter is sufficient.
<form method="POST" action="" onsubmit="javascript: return shout();" enctype="multipart/form-data">
<input type="text" style="width: 100%;" name="txtShout" id="txtShout" maxlength="600" autocomplete="off" title="Shout!" placeholder="Shout!">
</form>
The shout function looks like this:
function shout() {
alert("test");
// Post shout and clear textField
if(getLength("txtShout")) {
AjaxUpdate("./includes/shout.php?message=" + getItemValue("txtShout"), refreshShoutBox);
setItemValue("txtShout", "");
}
// Stop submit
return false;
}
Normally, the script should call the shout function, the AJAX would send a request to add the shout and then return false so the form does not get submitted.
But in all browsers except Google Chrome, the form gets submitted anyway. I put in an alert() in the function to check if it was called or a coding mistake but the alert is not being shown.
Well, for some reason, I couldn't get the onsubmit function working in other browsers. Instead of desperately keep looking to fix it a decided to go for a different approach. Now I just added a listener to the text box to check when a key is pressed if it was the enter key and then call that function.
That seemed to work, still had to remove the form though, because otherwise it would get submitted ^^.
So now I got something like this:
function shoutEnterListener() {
// Get object
var domObject = document.getElementById("txtShout");
// Get shoutbox html code
if(domObject) {
domObject.onkeydown = shoutEnter;
domObject.onkeypress = shoutEnter;
}
}
function shoutEnter(e) {
var keyCode;
// Check which key has been pressed
if (window.event) {
keyCode = window.event.keyCode;
} else {
keyCode = e.which;
}
// If enter, shout!
if (keyCode == 13) {
shout();
}
}
The shoutEnterListener() is called in the init function. This also proves that there wasn't a coding error whatsoever but purely the function not being called at all.
If you still find the solution to the previous problem, let me know, because this is a bit tedious and intensive code.
Related
here is the function from inside a script
function dosubmit()
{
if (getObj("Frm_Username").value == "")
{
getObj("errmsg").innerHTML = "Username cannot be empty.";
getObj("myLayer").style.visibility = "visible" ;
return;
}
else
{
getObj("LoginId").disabled = true;
getObj("Frm_Logintoken").value = "3";
document.fLogin.submit();
}
}
i want to get the value of getObj("Frm_Logintoken")
as i can't pull the value from #Frm_Logintoken
using document.getElementById("#Frm_Logintoken")
this gives me null
because Frm_Logintoken only gets it's value when i click submit .
<input type="hidden" name="Frm_Logintoken" id="Frm_Logintoken" value="">
full page code
i found this online /getObj\("Frm_Logintoken"\).value = "(.*)";/g
but when i run it ... it gives me the same line again !
it's full code
https://hastebin.com/gurosatuna.xml
First:
Your checking if a value is empty with JS. However this is NOT needed as HTML does this for you. Add a attribute required and the form will not submit as long this value is empty
Documentation: https://www.w3schools.com/tags/att_input_required.asp
Second:
You could use the event handler 'on submit'. The code is not complete enough to know if u did this but I suppose you just added a Click handler on the button.
Documentation: https://www.w3schools.com/jsref/event_onsubmit.asp
When combining these two, you always have a username filled in and the code only executes when submitted. I hope this helps, if not please leave a comment and I will edit this answer.
EDIT: the answer on this SO will also help (not the checked on but the one below)
How can I listen to the form submit event in javascript?
There are several questions/answers on this here, here and here and elsewhere, but they all seem JQuery specific and do not appear to apply to this (for example, I am NOT creating a new Form object, this is an existing form in the document. Also I am NOT using Jquery at all).
I have a form which has to be modified before submission for reasons of IE7 compatibility. I have to strip out all the BUTTON tags from my form and then add a hidden field, but this is all in an existing form on the existing HTML page. This code works properly in IE and Chrome but doesn't work in Firefox (versions 23 & 24 both tested).
buttonClickFunction(formName, buttonObject) {
var formObject = document.forms[formName];
var i = 0;
// Strip out BUTTON objects
for (i=0;i<formObject.length;i++) {
if (formObject[i].tagName === 'BUTTON') {
formObject[i].parentNode.removeChild(formObject[i]);
i--;
}
}
// Create new field
var newField = document.createElement('input');
newField.type = 'hidden';
newField.id=buttonObject.id;
newField.name = buttonObject.name;
if (buttonObject.attributes['value'] != null) {
newField.value = buttonObject.attributes['value'].value;
} else {
newField.value = buttonObject.value;
}
// Submit form
formObject.appendChild(newField);
document.forms[formName].appendChild(newField);
document.forms[formName].submit();
}
In addition to the document.forms[formName].submit() I have also tried formObject.submit() - both work in Chrome but both fail in Firefox. I'm at a loss as to why this doesn't work - I've traced through the JS and watched that document.forms[formName].submit() execute - no exception appears but nothing goes to the server.
Can anyone identify why Firefox won't submit this form, and how I can fix it?
Firefox expects that, when you submit a form, you have at least a submit button available, meaning there should be something like:
<button type="submit">Click me</button>
or:
<input type="submit" value="Click me" />
When you use the first one in your code, it will not work (because you strip out all buttons before submitting the form). When you use the second option, it will work, also in Firefox. As you can see in this fiddle: http://jsfiddle.net/q9Dzc/1/
I had similar behaviour, when form.submit() didn't work on Firefox, but worked on other browsers. Just make sure that all the buttons within form contain type="button".
For anyone having an issue with making the Firefox submit with the page location changing / reloading afterwards, you need to put your redirect code in the $.post callback:
$(".form").submit(function(e){
e.preventDefault();
$.post("submit.php", {data: textData}, function(){
history.go(-1);
});
return false;
});
If your form has a mixture set of "input [type=button]" and "button", the JavaScript of submit() will not work for "input [type=button]" sometimes.
I am making a text adventure game, which would require user input in the form of a element in html, which would send the user input to JavaScript using the click function:
<!-- HTML CODE -->
<div class="game">
<div id="gamebox">
<a name="game"></a>
<!-- Javascript writes to here (if it works :( ) -->
</div>
<div id="inputbox">
<input type="text" id="userinput" placeholder="Input" value="" />
Go!
</div>
</div>
As you can see above, I have a element and a "Go!" button, which sends it to my JavaScript code. In JavaScript, first I define 3 variables where I would output my text.
//JavaScript Code
var txt_input = $("#userinput");
var btn_quest = $("#btn-quest");
I would than define 2 other functions, which allows me to write into the . I would than have other functions, which are for the storyline of the text adventure game. However, the root of the problem is that I can't seem to progress past the second event. Here are my events:
function wakeUp() {
displayGame("You wake up, at stackoverflow. West or east? [Choose 'west' or 'east']");
btn_quest.on({
"click": function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "west") {
//Paste btn_quest here for new event
goWest();
} else if (input === "east") {
//Paste btn_quest here for new event
goEast();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
}
});
The first event function would work perfectly, and write to my html, and accept the first user choice. However, at the next event, no matter what it is, (goEast() or goWest()), my program aways displays "Error - enter a valid choice"). Right now, my hypothesis is that the "switch" function isn't working correctly. However, I honestly don't know. What is the issue here, and how can I fix it? The other event functions (etc goEast) are exactly the same as the wakeUp function, except with different displayGame() strings and link to other event functions.
I have not included the full code, in order to keep my code short - but here is the full html/css/javascript if needed: http://plnkr.co/edit/55heHh4k5QEIVYdBrWGB?p=preview
Edit: I tried to implement the suggestion, like this: But It seems that JavaScript doesn't even get the userinput anymore. When I try to submit the user's response, nothing happens. What went wrong? I did the same thing here with all of my functions in the game:
function wakeUp() {
displayGame("You wake up at stackoverflow again, but it didn't work. Go West or east again?");
// btn_quest.off("click").on("click",function()){
btn_quest.off("click").on;
"click", function() {
// Begin input preproccessing
var input = txt_input.val().toLowerCase();
// If/else block for choice here
if (input === "walk") {
//Paste btn_quest here for new event
walkToWork();
} else if (input === "bus") {
//Paste btn_quest here for new event
busToWork();
} else {
//Error handler - do not modify
txt_input.val("Error - enter a valid choice");
}
//End of if else block body
};
//End of function. Copy until line under this comment V
}
What did I do wrong? Can you please show a example using this function?
You need to look at all the code to see the problem. The reason is because you keep binding to the element so multiple click events are being triggered. You need to remove the last click
btn_quest.off("click").on("click",function(){});
I want to make a custom made confirmation box in javascipt just like the built in confirm box. the built in confirm box does not allow the code to progress unless the user selects atleast one thing. Below is my code:
*****HTML start*****
<div class = "popUp confirm" style="z-index:40000;" id="confirmBlock">
<div id = "confirmLabel" >Confirm Message</div>
<div style ="border:0px solid red;height:44.56px;">
<input id="Confirm" type="button" value="Confirm" onclick = "confirmAction(1)" />
<input id = "CancelConfirm" type="button" value="Cancel" onclick = "confirmAction(0)" />
</div>
</div>
*****HTML end*****
*****Javascript start*****
var confirmresult = "-1";
function confirmationLoop()
{
alert("If this alert is preesnt it works, seems like the built in alert provides some sort of pause for other parts of code to continue to work");
if(confirmresult == "-1")
confirmationLoop();
return;
}
function confirmAction(val)
{
confirmresult = val;
}
function checkuuu()
{
confirmresult = "1";
}
function confirmMessage(message)
{
document.getElementById("confirmLabel").innerHTML= message;
//var check = setTimeout(function(){confirmAction(1)},5000);
confirmationLoop();
/*
while(1) //using while almost does not allow any other part to run at all hence tried recursion
{
if(confirmresult != "-1")
break;
}
*/
document.getElementById("confirmLabel").innerHTML= "Confirm Message";
var returnVal = confirmresult;
confirmresult = -1;
return returnVal;
}
*****Javascript end*****
*****Sample code start*****
So this i what i expect below:
function example
{
var check = confirmMessage(message);
//the next part of code should not execute untill i press confirm or cancel, using settimeout or settimeinterval is asynchronous and the code flow continues. i want the effect something like alert and confirm built in boxes
}
*****Sample code end*****
I used loop but it keeps the thread completely occupied and does not give me a chance to press any button, which was quite obvious
However recursion gives u the freedom to perform other activities. The problem even though the value of confirmResult will become 1 upon pressing confirm button, which i check through alert. the recursive loop i.e. confirmation loop does not seem read it as 1. it still continues as -1. If i put a alert in that confirmation loop the value wil be read as 1. Can anyone help me to achieve what i started out to??????
P.s.=> sorry for such a huge question!!!
You can't use any sort of loop - as you've found it'll just cause the browser to lock up.
What you need to do is to emulate a "modal" dialog box.
This is usually done by having your dialog box appear on top of another "overlay" element which importantly covers every other element, and prevents any user interaction with them.
It's also pretty hard to implement a confirm function that'll return a value - the window.confirm method can only do that because it's synchronous - it blocks all other JS processing while the dialog is displayed.
The easiest approach is to instead supply a callback function that'll get called once the user has selected the desired value.
I have a simple html form with few fields in it.
I wanted to make sure that user gets an alert message when he is trying to leave the page. So I added the script on the page which will run whenever user is trying to navigate away from this page.
But I am also getting this alert message when user is trying to submit the form. I dont want this alert message when user is saving the form.
Please help.
Below is some sample code.
<html>
<head>
<script>
function verifyexit() { return 'Are you sure ?'; } window.onbeforeunload = verifyexit;
</script>
</head>
<body>
Go to another page
<form action="c.html">
name : <input type="text" name="name" value=""/> <br>
email : <input type="text" name="email" value=""/> <br>
<input type="submit" value="save"/>
</form>
</body>
stackoverflow reference
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
With JQuery this stuff is pretty easy to do. Since you can bind to sets.
Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.
To make this work in Chrome and Safari, you would have to do it like this
window.onbeforeunload = function (e) {
e = e || window.event;
var msg = "Sure you want to leave?";
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
};
This is the general rule in reference
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE<8 and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Chrome, Safari, IE8+ and Opera 12+
return 'Any string';
};
reference: https://developer.mozilla.org/en/DOM/window.onbeforeunload
Try this:
<form action="c.html" onsubmit="window.onbeforeunload=function(){}">
Try this:
$(window).bind("beforeUnload", verify);
$("form").submit(function (){
$(window).unbind("beforeUnload");
};
Try this: http://cfsilence.com/blog/client/index.cfm/2009/10/12/jQuery-Method-To-Prompt-A-User-To-Save-Changes-Before-Leaving-Page
I added another bit to the function:
$('#submitButton').click(function () {
isDirty = false;
});
Just so the form doesn't ask for validation when you want to submit it :)
I hope this helps
Note: You could also do something like $("input[type=submit]") if you don't like to depend on a common naming (else your submit button needs to be called submitButton)