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.
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?
I'm working on a shopping cart that asks the user to check the box indicating they agree to the terms of service before they can "review order" and finally make the purchase.
I have to accomplish this with JavaScript by getting the element containing the "review order" and "continue shopping" buttons and changing the inner HTML to be what I need. I have to do it this way because the cart I am using does not give me full control over these elements in the cart source code.
Here is the code I originally came up with, which worked on Chrome, Edge, and other browsers, but not IE.
var x = document.getElementById('CHECKOUT_LINKS');
x.innerHTML = '<div class="checkoutLinksBottom"><input id="tosBox" type="checkbox" name="tosBox">I agree to the Terms of Service<br>Continue ShoppingReview Order</div>';
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#tosBox').addEventListener('change', changeHandler);
});
var checkbox = document.getElementById("tosBox");
checkbox.checked = true;
checkbox.checked = false;
function changeHandler() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
}
function clicker() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
else { // Go to review order page
}
}
As you can see the CHECKOUT_LINKS element's inner HTML is changed to what I need on the fly as the page loads. The primary point is to add the id="tosBox" element, then capture the click on id="reviewOrderButton" element and filter it though the simple JS functions changeHandler() and clicker().
In IE developer tools, the console reports 'tosBox' is undefined when I click on id="reviewOrderButton" element. This makes sense when looking at var checkbox = document.getElementById("tosBox"); the variable created is called checkbox, but the variable I try to use later is called tosBox. I simply changed checkbox to tosBox and then everything worked on IE as well.
What's shocking to me is that the original code worked on Chrome and Edge. How did it work? Should I expect it to work and IE is faulting?
This one really has me scratching my head.
I'm building a calculator using JavaScript as an exercise. Said calculator is up and running here on Codepen. In the lower left you will see a "+-" button, which simply takes the content of the input field, and reverses it's sign (positive becomes negative, negative becomes positive.) Then when the user presses an operation button this is pulled and used in the calculation. Simple right?
The function which actually changes the sign is as follows:
function toggleSign() {
if(getCurrentDispVal()[0] === "-") {
currentNumStr = currentNumStr.slice(1, currentNumStr.length);
} else {
currentNumStr = "-" + currentNumStr;
}
updateDisplay(currentNumStr);
}
and is called in just one place, a function which takes input from the user and decides what to do with it:
function useInput(input) {
if(input.match(/(\d|\.)/)) {
handleDigitInput(input);
} else if(input.match(/(X|\/|-|\+)/)) {
handleBinaryOperation(input);
} else if(input.match(/=/)) {
handleEqualsOperation();
} else if(input.match(/^c$/)) {
clearCurrentNumStr();
} else if(input.match(/^ac$/)) {
allClear();
} else if(input.match(/^shorten$/)) {
shortenCurrentNumStr();
} else if(input.match(/^plusmin$/)) {
toggleSign();
}
}
Now sometimes, and only sometimes, this works as expected. For instance, enter the following:
1 on keyboard, not the screen
Click the "+-" button
+ on keyboard
5 on keyboard
enter on keyboard
Sometimes this runs properly, and spits "4" as the result. Sometimes, and this is baffling me, when you hit enter it flips the sign on "5" making it "-5" and then returns "-6" as the answer." I've done some checking and can see that when this occurs, in the useInput function both the /=/ and /^plusmin$/ conditionals are being triggered. Thus toggleSign is being called prior to handleEqualsOperation and this is lousing up the results. Strangely, if you don't use the keyboard, and just click the screen buttons directly, this problem doesn't occur.
I'm at a loss here. There doesn't seem to be any pattern as to when this occurs, and I'm using the same input above over and over. I don't understand why this is occurring, and why it isn't occurring consistently.
So for what I can see, there is a problem in the way you handle the "currentNumStr" variable, follow this example, to find another problem:
press 5
press the +/- button to toggleSign
press the X button
press 6
"It will display -30", but since you made an operation (handleBinaryOperation, handleEqualsOperation) "currentNumStr" will be empty"
press the +/- button to toggleSign
you will get an empty display
If you track this variable you'll get your answer.
Also keep in mind that e.key is not cross-browser compatible, maybe you could use e.keyCode or e.which instead, I got many undefined errors because of this.
EDIT: To exemplify what I added in the comments:
in the HTML change this:
<div class="calc-body>
to this, choose the id you want ( the tabindex is necessary so the div cant get the focus)
<div class="calc-body" id="forFocusId" tabindex="0">
and in the Js file, add a global var to assign the div ( if you dont want to add a variable, you can call document.getElementById("forFocusId") in the next step instead)
var focusElement = document.getElementById("forFocusId");
finally at the end of the function useInput, add
focusElement.focus();
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(){});
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create TRULY modal alerts/confirms in Javascript?
TL;DR: I've overridden the default alert() function with a custom HTML based one. I want the new dialogue to still block execution, and get the buttons within my dialogue to return true or false from the call to alert() to use in logic (and continue execution).
I'm trying to implement a custom alert box, which replaces the default browser alert with a nicely themed box with the same (or similar) functionality.
I've read this question, and I'm using the solution given in this answer (to the same question). What I want to do now is get my overridden alert to return a true or false value for use in if() statements, depending on whether OK or Cancel was clicked:
if(alert('Confirm?') {
// Do stuff
}
However, due to having custom HTML instead of a normal alert I can't do this for two reasons:
I can't return a value from the buttons in the replacement dialogue (click events bound with $.on()) because I have no idea how to.
I can't block program flow with this alert, as far as I know.
I've bound $.on() events to the Cancel and OK buttons in the replacement dialogue which hide the box. These work fine, but the problem I have now is returning a value when a button is clicked, so that execution will halt until an action is taken by the user.
HTML:
<div class="alert background"></div>
<div class="alert box">
<div class="message"></div>
<hr>
<div class="buttons">
<input type="button" name="cancel" value="Cancel">
<input type="button" name="confirm" value="OK">
</div>
</div>
Current JavaScript: (pretty much a carbon copy of the answer in my linked question)
(function () {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
(function (proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null' : arguments[0];
var type = (!arguments[1]) ? '' : arguments[1];
if (type && type == 'native') {
nalert(message);
} else {
// Custom alert box code
console.log(message);
}
};
})(this);
Ideally, I want to be able to put something like this in the // Custom alert box code part:
$('.alert.box input[name="confirm"]').on('click', function() {
// Hide dialogue box - I can do this already
// *** Return `true` or other truthy value from
// alert for use in `if()` statements
});
So that when the OK or Cancel button is clicked, it removes the custom alert box and returns a true or false value from the call to alert(). I can already remove the alert with $.fadeOut() and $.remove(), that's easy. What isn't is knowing how to get the button click events to get alert() (overridden) to return something.
I've tried to be as clear as I can, but I may have missed something out. Please let me know if I have.
The example below shows an approach to creating a custom alert and handling the outcome of the user selection
/*
message = String describing the alert
successCallBack = callback function for when the user selects yes
*/
function exampleAlert(message, successCallback)
{
/*Alert box object*/
var alertBox = document.createElement("div");
/*Alert message*/
var msg = document.createElement("div");
msg.innerHTML = message;
/*Yes and no buttons
The buttons in this example have been defined as div containers to accentuate the customisability expected by the thread starter*/
var btnYes = document.createElement("div");
btnYes.innerHTML= "Yes";
/*Both yes and no buttons should destroy the alert box by default, however the yes button will additionally call the successCallback function*/
btnYes.onclick = function(){ $(this.parentNode).remove();successCallback();}
var btnNo = document.createElement("div");
btnNo.innerHTML= "No"
btnNo.onclick = function(){ $(this.parentNode).remove();}
/*Append alert box to the current document body*/
$(alertBox).append(msg, btnYes, btnNo).appendTo("body");
}
function test()
{
alert("Example alert is working, don't use this test as a replacement test - horrible recursion!")
}
exampleAlert("shoe", test)
This is fairly basic and doesn't allow for additional data to be supplied to the callback function and for that reason is not ideal for production however jQuery's .bind() and similar methods allow for data to be associated with the callback method
It's worth commenting that while the above demonstrates a full implementation of the problem, there are in fact only two lines that actually matter.
btnYes.onclick...
btnNo.onclick...
Since we're achieving the desired result by binding onclick events for true and false respectively, everything else is there to paint the picture.
With that in mind it is possible to effectively turn any container object with at least one sibling into an alert box for eaxmple:
<!-- Example html -->
<div id='a'>
<ul>
<ul>
<li>Something</li>
<li>Something Else</li>
<li id='yesIdentifier'>Something not necessarily suggesting a trigger?</li>
</ul>
</ul>
</div>
As long as your yes / no (if no exists) options destroy the appropriate container a converting a container into an alert box can be handled in a couple of lines of code.
$('#yesIdentifier', '#a').click(
function(){ someCallback(); $(this).closest('#a').remove()});
Neither of the above are exemplary models for implementation but should provide some ideas on how to go about the task.
Finally... do you really need to replace the native alert method? That is, either you're writing the alert calls, in which case you'd know to use your custom method, or you're overwriting default behaviour that you can't guarantee the other developers will be aware of.
Overall recommendation:
I feel the best approach to this would be to create a jQuery plugin which creates the custom alerts on the fly and track callbacks, results and what not within the plugin.
SOliver.
Why don't you just use a confirm box like so.
var c = confirm('Confirm?');
if(c)
{
// Yes clicked
}
else
{
// No clicked
}
Or you could use jQuery UI's dialog confirmation box.
http://jqueryui.com/demos/dialog/#modal-confirmation