Problems with javascript / window.confirm function - javascript

I have an HTML button that calls the checkTax() function.
The function should either confirm and proceed with the form submit when OK is clicked, or cancel the submission and redirect the user to a different page.
This is the function:
function checkTax () {
if ( CUSTTAXRATE == 0 ) {
var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
if (r == true){
return true;
}
else {
<!--- return false; --->
window.location.replace("index.cfm?action=retailQuote.settings");
}
}
}
I have tried both just cancelling the submission or redirecting it, but I cant get either to work. Both ways still submit the form and proceed.
What am I doing wrong??

Make sure you use a return statement in the button's onclick attribute.
<button type="submit" onclick="return checkTax();">Submit</button>
Otherwise, the return value from the function will be ignored, and it won't prevent the form from submitting when it returns false.

I have tried completing the answers above for your simplification.
Please find the code below :
<body>
<form action="">
<input type=text id="t1">
<button type="submit" onclick="return checkTax();">Submit</button>
</form>
<script type="text/javascript">
function checkTax() {
var CUSTTAXRATE = document.getElementById("t1");
if (CUSTTAXRATE == 0) {
var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
if (r == true) {
return true;
} else {
window.location
.replace("index.cfm?action=retailQuote.settings");
return false;
}
}
}
</script>

Related

How can I make it so that when input field is empty, button does nothing?

I'm making a simple searcher in which the user enters a query, clicks search, and the program returns either the location of said element, or a "No results found" line.
I'm having trouble with the search button itself. It works perfectly fine when the element that is being searched exists, but if I click on it while the input is blank, it returns the "No results found" message. I would like it so that it does nothing.
I'm using mainly JavaScript. What I've tried so far is make an if statement to check the length of the input, and then select the element from the DOM and make it disabled when length is 0.
I have tried adding both console.log and alert() to check the state of the button (enabled/disabled), and they both work equally, no matter the length of the input value.
<button value="submit" id="button" data-key="13" onclick="clickFunction()">
</button>
function clickFunction() {
var input = document.getElementById('input_id').value;
var input = input.toLowerCase();
/* disables button if there is no input */
if ( input.length === 0 ) {
document.getElementById("button").disabled = true;
console.log("disabled");
} else if (input.length > 0) {
document.getElementById("button").disabled = false;
console.log("enabled");
}
}
I have also tried using jQuery ($("#button").attr("disabled", true)), but it's not working either.
Am I missing something?
You need to stop the click, disabling the button with click means you will not be able to enable it.
function clickFunction(evt) {
var input = document.getElementById('input_id').value.trim();
// if (!input.length) { evt.preventDefault(); }
if (!input.length) return false; // cancel click
return true
}
<form>
<input type="search" id="input_id" name="input_id" />
<button value="submit" id="button" data-key="13" onclick="clickFunction(event)">
</button>
</form>
but why use JavaScript, let HTML do it for you.
<form>
<input type="search" name="search" required />
<input type="submit" />
</form>
this should work
function validate(obj) {
if (obj.value.length > 0) {
document.getElementById("btnSave").disabled = false;
} else {
document.getElementById("btnSave").disabled = true;
}
}
<input type="text" id="txtName" onkeyup="validate(this)"/>
<button disabled id="btnSave">save</button>
You can modify your code in this manner:
function clickFunction() {
var input = document.getElementById('input_id').value;
input = input.toLowerCase();
if (input.length) {
// write your search logic here
} else {
// won't do anything
return false;
}
}
I hope it will help.

Multiple onClicks in Submit Button

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

Click button. Javascript alert box. If click OK, page reloads and need to create php variable with html input form value

User clicks on Delete button. Javascript alert box popups with OK and Cancel. If user clicks OK, then page reloads (post form) and I need to create php variable with value from here name="confirm_delete")
Here is my code
<form action="<?php echo (htmlspecialchars($_SERVER["PHP_SELF"])) ?>" method="post">
<input name="delete" type="submit" id="delete" value="Delete">
<input type="hidden" name="confirm_delete" id="confirm_delete" value="0" >
<script>
$(document).ready(function() {
$("#delete").click(function(){
var answer = confirm("Are you sure you want to delete?");
if (answer){
return true;
document.getElementById('confirm_delete').value = 1;
} else {
return false;
document.getElementById('confirm_delete').value = 0;
}
});
});
</script>
Then print_r($_POST['confirm_delete']); but value always is 0. That means that document.getElementById('confirm_delete').value = 1; does not work.
Please, advice what need to correct
Replace your javascript code by following:
<script>
$(document).ready(function() {
$("#delete").click(function(){
var answer = confirm("Are you sure you want to delete?");
if (answer){
document.getElementById('confirm_delete').value = 1;
return true;
} else {
document.getElementById('confirm_delete').value = 0;
return false;
}
});
});
</script>
You are using the return true and false first after that you are assigning the value. so return terminates from the function before assign the value. so first assign the value and then use the return.

I have to press submit button twice in IE using jquery framework to submit form

I have a strange behaviour in IE browser.
I have simple form:
<form name="test" id="test" action="some_url_here" method="post">
<input type="text" name="url" id="url" class="required" />
<input type="text" name="page" id="page" class="required" />
...
<input type="submit" name="submit" value="Submit" />
</form>
and in JS:
var result = true;
$("#test").on("submit", function(){
$(".required").removeClass("error");
$.each($("input.required"), function(k, v) {
if($(this).val() === '') {
$(this).addClass("error");
result = false;
return false;
}
});
if(result) {
if(!IsValidUrl($("input[name='url']").val()){
$("input[name='url']").addClass("error");
return false;
}
} else {
return false;
}
});
Let's assume that I filled all fields correctly.
In Chrome & Firefox, when I press on submit button then works fine, just once time.
In IE (all versions) I have to press two times on the submit form to execute/sumbit the form.
Why ?
I tried also to put after IsValidUrl condition:
$(this).submit();
But no success.
You have two options here. On both you need to stop the submit event and validate the form.
One is to go through all the fields in the form, add the class error to the invalid ones (if there's any), set the variable result and return (or submit if everything is alright).
The other is to stop the test at the first invalid field found, not using the variable result, and return (or submit if everything is alright).
JS
$(function () {
$("#test").on("submit", function (e) {
// Stop the submit, because you need to validate the form before proceeding.
e.preventDefault();
// Check the comments below to decide for the use of the variable.
var result = true;
$(".required").removeClass("error");
$.each($("input.required"), function (k, v) {
// Test for empty fields or, if it's the URL, check whether is valid.
if ($(this).val() === "" || ($(this).attr("name") == "url" && !IsValidUrl($(this).val())) {
// Add class error to the invalid fields.
$(this).addClass("error");
// At this point, you could just return false stopping the loop,
// or keep going to make sure all the invalid fields will get the
// class error. In this case, you can still use the variable result.
result = false;
// Keep going, so, no return.
// return false;
}
});
// If you decided to carry on through all the fields, and don't return
// false at the first error, test for the result value.
// As this is the case...
if (!result) return false;
else $(this).submit();
// If you didn't return previously...
// $(this).submit();
});
});

Onclick event; If and Else

All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)

Categories

Resources