Javascript confirm ain't working as it should - javascript

I have this js function that checks if OK or Cancel is pressed and returns false or true. What I am trying to do is that when is true to run the remaining js function in the order they appear but it isn't working; deleteList('$row->listID');updateList(); are never executed.
Javascript:
function deleteConfirm(){
if (confirm("Are you sure you wanna delete that list?")){
return true;
}
else{
return false;
}
}
HTML:
<a href="#" id="listID" onclick="return deleteConfirm();deleteList('$row->listID');updateList();">
What am I doing wrong?
Thanks in advance.

It's because you're returning on the first statement (so the others never run), instead only hop out on a cancel, like this:
onclick="if(deleteConfirm()) { deleteList('$row->listID'); updateList(); }"
You can also greatly simplify your function, like this:
function deleteConfirm(){
return confirm("Are you sure you wanna delete that list?");
}
...or if possible go the unobtrusive route, using data- attributes to get the listID.

Related

javascript: confirm functionality with my own confirm box and function

if (confirm('ARE YOU SURE?')) {console.log('sure');}
else {console.log('not sure');}
I want this functionality with my own confirm box and my own function
<div class='mdialog' id='mdialog'>
<div id='dgcancel' onclick="???">CANCEL</div>
<div id='dgok' onclick="???">OK</div>
<div id='dgquestion'>//here is the question</div>
</div>
if (conf('ARE YOU SURE?')) {console.log('sure');}
else {console.log('not sure');}
function conf(){
// ???
}
Could someone help me to accomplish this?
The question you are trying to point is unclear. Using confirm function leads you to a confirmation dialog box answering ok and cancel.
Another is using a div tag for a confirmation of ok and cancel. You can change this into button.
I made some changes to your code an created a pen you can visit, and try to play around with it.
function myFunction(x) {
if (x == "ok") {
var conf = confirm("Are you sure You want to delete this item");
if (conf == true) { //this block means the user clicked the "OK" in the confirmation dialog box.
//Some statement here
//example alert statement
alert("Item has been successfully deleted!");
}
}
if (x == "cancel") {
var cancel = confirm("Are you sure you want to cancel");
if (cancel == true) {
alert("Item deletion has been cancelled");
}
}
}
<div class='mdialog' id='mdialog'>
<div id='dgquestion'>
<h1>Do you want to Delete this item?</h1>
</div>
<button onclick="myFunction('ok')">OK</button>
<button onclick="myFunction('cancel')">CANCEL</button>
</div>
You have the skeleton for your html.
Instead of ??? put there something replaceable, like {{cancelCallback}}, {{okCallback}}, {{question}}.
Then, create a Dialog class that you can instantiate. Here's a great place to start: What techniques can be used to define a class in JavaScript, and what are their trade-offs?
The class should take as parameters 3 things (not necessarily in this order):
a function that gets called when the cancel is clicked
a function that gets called when ok is clicked
the actual question
This class, when instantiated, should display, or inject, the HTML skeleton in the DOM and at the same time replace the {{}} variables with the actual functions/string.
You should be able to have a "dispose" method to this class.
And prepare for the future: maybe you add more buttons - make it expandable. Etc.
Have fun!
And I hope you did not expect to actually provide the code for that, as that's not
the purpose of StackOverflow :)

How to render a new page in a javascript script

I am using XHTML, JSF and JavaScript to create a form, validate that information has been submitted into selected fields onclick in a h:commandButton, and if validated, redirect to a different page homepage.xhtml. Everything works up to the redirection, which I can't get to work.
In the JavaScript function Validation(), I have tried location="homepage.xhtml", window.location.href="homepage.xhtml", location.url="homepage.xhtml" and a few others, but nothing seems to work. I have a feeling I'm supposed to have some sort of statement which adds href="homepage.xhtml" to the h:commandButton if Validate() returns true, but I am unsure as to how to do that.
Any help is greatly appreciated. I have added the relevant code below.
Button:
<h:commandButton class="btn btn-warning" value="Continue" onclick="Validation()"/>
Validation
function Validation() {
var nameCheck = document.getElementById('formdiv:cardName');
var numCheck = document.getElementById('formdiv:cardNumber');
var expCheck = document.getElementById('formdiv:expDate');
console.log(nameCheck.value);
console.log(numCheck.value);
console.log(expCheck.value);
var variablesToCheck = [nameCheck, numCheck, expCheck];
for(i=0; i < variablesToCheck.length; i++){
if(variablesToCheck[i].value == null || variablesToCheck[i].value == ""){
alert("Fields marked with a * must be completed");
return false;
}
}
// This is where the redirection needs to go, I think...
return true;
}
EDIT: Just noticed the if else statement is incorrect logically, but syntactically it shouldn't make a difference. The else part needs to be a statement outside of the loop without a condition; this code simply tries to redirect when the field it is checking has something in, not when all fields have something in.
EDIT 2: Loop corrected
Why you need h:commandButton anyway you are using simple javascript validation
h:commandButton is rendered as <input type="submit" ../> its mission is
to submit the form so what ever javascript you are writing your form will be submitted and your page is gonna be refreshed, So If you need it this way you have to force it not to submit the form,
However from understanding your needs all you need is simple <a /> or <button /> , Or you can just add type="button" into your h:commandButton ex:<h:commandButton type="button" .../>
You can either use..
window.location.replace('Your_url'); ..
or you can use..
window.location.href= 'Your_url'; .. I guess there must be other functions too. If you want to open it in another window, like a popup, you can use.. window.open('your_url');
Hope this helps!

Checkbox can't be unchecked

I am currently trying to solve a problem with my jquery and my html form.
Problem: I have a checkbox that allows people to check to accept or not accept the terms and conditions. This checkbox is being validated by a jquery function, named validateAccept(). However, after i insert the if valid return true and if not valid return false, the checkbox become unresponsive to clicking. I am a beginner with jquery. I am not sure which part went wrong.
my HTML code:
<form action="<? echo $filename; ?>" id="acceptanceForm" name="acceptanceForm" method="post">
<p>Terms and conditions.......</p>
I ACCEPT THE TERMS AND CONDITIONS
<input type="checkbox" name="accept" id="accept" value="yes"/>
<span id="acceptInfo" class="inputInfo"></span>
</form>
My jQuery validating code:
$(document).ready(function(){
//Validation (TERMSANDCONDITION)
//termsandconditions variables
var acceptanceForm = $("#acceptanceForm");
var accept = $("#accept");
var acceptInfo = $("#acceptInfo");
//Trigger validation
//On blur
accept.click(validateAccept);
//On key press
accept.keyup(validateAccept);
//On submit
acceptanceForm.submit(function () {
if (validateAccept())
return true
else
return false;
});
//Validation
//validate accept
function validateAccept() {
var isChecked = $('#accept').is(':checked');
if (isChecked) {
accept.removeClass("error");
acceptInfo.text("Thanks");
acceptInfo.removeClass("error");
acceptInfo.removeClass("inputInfo");
acceptInfo.addClass("validated");
return true;
} else {
accept.addClass("error");
acceptInfo.text("Please Read and Accept the Terms and Conditions");
acceptInfo.removeClass("inputInfo");
acceptInfo.removeClass("validated");
acceptInfo.addClass("error");
return false;
}
}
What I know:
I know that the problems lies with the return true and return false that I added in. I tried without them on JS Fiddle and the check box is working but the form is not. Therefore, I know that return true and false is necessary but I don't really know how I should sort them out to make it work. I have did some researched and realised that little little cases similar to mine. This validation technique is suppose to work on text input so I am not sure if the way i edit it is alright to work for checkbox.
JSFiddle
The problem is that returning false in a click handler prevents the default behavior. If you need to use this in both situations, but ignore the return value in the case of the click handler, you could do this:
accept.click(function(){
validateAccept();
});
http://jsfiddle.net/8JdRb/1/
In this case the click handler function has no return value and does not affect the functioning of the checkbox.
I found the answer. I can use .change(validateAccept); instead. It would work exactly the same as I wanted to. Thanks all.
JSFiddle

Why is this working?

I have written some simple javascript to change the content of an iframe according to the input of a field. After hours of attempts, I have managed to get it working; however I didn't really understand why I should put the "return true" and "return false" at the end of my search function. Thank you in advance!
function search(){
var course=document.getElementById("field");
if(course.value!=""){
if(course.value!="Course code (e.g. COMP1004)"){
var target=document.getElementById("frame");
target.src=course.value + ".php";
return false;
}
}else{
return true;
}
}
<input id="field" name="field" type="text"></input>
<input id="searchButton" name="searchButton" type="button"value="Search"onclick="search()"></input>
You don't really need to, since you are calling the function without expecting any value. And even if you write onclick = return search() you have no default action to prevent, since your input has type="button"
When you trigger a javascript function using onclick (depending on the browser), the actual functionality of the click can be prevented by returning false. So if you click on a button and return true (or nothing) the actual click will be triggered and e.g. load a new page. If you return false, the original function of the button will not be called ...

How to disable Link for some time after being clicked?

To prevent impatient users from clicking on a link to a webstart application too often, I tried to disable the hyperlink for some seconds after it has been called the first time.
<a href="file.jnlp" onclick="if (!this.clicked){this.clicked = true; setTimeout('this.clicked = false' ,10000); return true;} return false">
The code above only works for disabling the link, but it doesn't get re-enabled after the timeout of 10 seconds.
I've seen that the 'this.clicked' variable isn't true (as it is supposed to be) when I check it in the setTimeout call. Maybe i'm missing some basic JS-knowledge here..
Or perhaps there is a different approach to solve this problem?
First add a this function to a Javascript Script block
function Debounce()
{
var self = this
if (this.clicked) return false;
this.clicked = true;
setTimeout(function() {self.clicked = false;}, 10000);
return true;
}
Now change your onclick to:-
onclick="return Debounce.call(this)"
using your code modifying only a small part it may work
<a href="file.jnlp" onclick="if (!this.clicked){this.clicked = true; setTimeout(function(){this.clicked = false;} ,10000); return true;} return false">
looks like people say that didnt work and it didnt form a closure around 'this'
The this object is not defined in the code being evaluated by setTimeout which is done in the global scope.
Give the link an ID then use getElementById e.g.
<a href="file.jnlp" id='my_link' onclick="if(!this.clicked){this.clicked = true; setTimeout('document.getElementById(\'my_link\').clicked = false;' ,10000); return true;} return false;">
give this anchor an ID and then change your timeout call to:
setTimeout('document.getElementById("<id>").clicked = false;' , 10000);
I think the 'this' is not evaluated to anything when the timer comes around.
var a=this;
setTimeout(function(){a.clicked = false} ,10000);

Categories