sweet alert message in JavaScript is showing for a split second - javascript

When user press confirm button,
i need to check a few things using javascript and in a certain condition need to show sweet alert
in which, once the user will press ok (in the sweetalert message) it will redirect to another page.
but the alert is showing for a split second and not redirecting to the page(since i didnt press "ok").
javascript is called from onClick of a button in the view:
<div class="col">
<button type="submit" class="btn btn-primary form-control" onclick="ApprovePayment()">Create</button>
</div>
here is the javascript in the view :
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment() {
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}

The onclick listner is defined on the submit button, when you click on the submit button the browser will perform the default action which is the form submit.
To prevent this you can use two approaches.
Add the listener on the form onsubmit.
Prevent the browser default action.
Change the button type from submit to 'button'.
Example for the second method.
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script src="https://cdn.tiny.cloud/1/h0b6kdvecrt66vsb30f5tpqd7ocxoezkzq6fcfbbvp0xrbfw/tinymce/5/tinymce.min.js"></script>
<script type="text/javascript">
function ApprovePayment(event) {
event.preventDefault(); // stop the default action
var val = document.getElementById("PaymentHistory_SentFromAddressId");
var selectedText = val.options[val.selectedIndex].text;
var amount = document.getElementById("PaymentHistory_Amount");
var value = parseFloat(amount.value);
var max = parseFloat(amount.getAttribute("data-val-range-max"));
var min = parseFloat(amount.getAttribute("data-val-range-min"));
if (!(value < min || value > max)) {
window.alert("amount validated");
if (selectedText.includes("- Paypal")) {
window.alert("in paypal")
}
else {
swal("Success!", "Payment Added To Your List, Admin will Approve once Payment Received!", "success")
.then((value) => {window.location.href = '/UserRole/PaymentHistory'; });
}
}
}
</script>
}

Related

How to enable disabled the submit button using JavaScript or jQuery?

I have a form Data in the HTML like the below,
Blade file:
<form method="post" action="someURL" id="register">
<input type="text" name="name" id="name" />
<div class="error">{{ $errors->first('name') }}</div>
<input type="email" name="email" id="email"/>
<div class="error">{{ $errors->first('email') }}</div>
<textarea name="body" id="message"> Enter your message here</textarea>
<div class="error">{{ $errors->first('message') }}</div>
<input type="submit" id="btnSubmit" disabled />
</form>
<script>
const button = document.querySelector("#btnSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
let startButtonStateCheck = () => {
button.dataset.interval = setInterval(updateButtonState, 1000);
}
let updateButtonState = () => {
let expirationDate = new Date(button.dataset.enabledAt);
if (expirationDate < new Date()) {
button.disabled = false;
clearInterval(button.dataset.interval);
} else {
button.disabled = true;
}
}
let buttonDisableExpiration = localStorage.getItem(buttonExpirationDataKey);
if (!buttonDisableExpiration) {
// no button state in localStorage, enable button
button.disabled = false;
} else {
// button state held in localStorage, check every 1s for expiration to enable the button again
button.dataset.enabledAt = buttonDisableExpiration;
updateButtonState();
startButtonStateCheck();
}
button.addEventListener("click", () => {
var form = document.getElementById("register");
var fields = ["name", "email", "body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (form[fieldname].value === "") {
button.disabled = false;
}
else{
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 10;
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
startButtonStateCheck();
}
}
});
</script>
In controller::
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
I have validated the fields in the controller.
The Submit button on click should check whether all the Input Values were given, If either one of the values is missing, the Submit button should be Enabled, even on click. I have given the validation in the controller
In my code, the submit button is disabled every time, when it is clicked even without the input values. But, it shows the error as This field is required near the input fields, when we click the submit button.
I need the submit button to be Disabled on click, when all the input values were given and then storing the button Enabled and Disabled in the Local storage.
When a user submits the form, without entering the form input, the button should be Enabled.
But, the submit button is not working as expected. It gets disabled, even without the form inputs
How could I do this? Could anyone please help?
Here first you will have to prevent the default action of the form so you need to use preventDefault() on event and than after all validations check you can manually submit or enable the button. But the main thing is that you need to disable the default behaviour to add your own custom checks.
Here is a fiddle to show :
https://jsfiddle.net/g6wfkj74/7/
Hope this helped

Confirm deletion alert code not quite right

I'm creating a simple todo app in JS and i've added an alert box to confirm deletion when usr clicks the delete button. If user clicks 'OK' it deletes fine, and if clicked 'Cancel' it won't delete but it creates another empty
li tag under it.
Something is not quite right with my deleteItem function but I can't figure out what, tried adding an else statement same thing happens. Any help with an explanation will be greatly appreciate (I'm a noob in JS as you can tell). Thanks!
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
What you need to change is: make the buttons of the list items of type button. They default value of type for a button is submit, which will submit the whole form, which will trigger your issue.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)" type="button">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
You forgot to close the form tag after the button, as a result your ourForm listener gets called even for confirmation box.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
</form>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>

Problems with javascript / window.confirm function

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>

Change button type to submit

I'm trying do something like this:
Initially, the user has button "Edit booking", but after clicking on it something activates and button becomes a submit button. When the user enters his info and clicks submit, this data goes to servlet.
It works partially, but the problem is that when the button changes, I don't have a moment when the user can enter their data.
Here is my current code:
<c:if test="${booking.status == 'Checking'}">
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="editButton"
onclick="activate(); changeButton();">
</form>
<script>
function activate() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
editButton.setAttribute('type','submit');
}
else {
document.getElementById(editButton).action = "/BookingUpdate";
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
}
}
</script>
<script>
function changeButton() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
editButton.value = "Submit";
}
else {
editButton.value = "Edit booking";
editButton.setAttribute('type', 'button');
}
}
</script>
</c:if>
Actually, you can submit a form data by either using a submit button or calling a submit function document.getElementById("myForm").submit()directly in javascript code.
thus, you can try something like below:
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="smartButton" onclick="doSomethingSmart();">
</form>
<script>
var smartButton = document.getElementById("smartButton");
var myForm = document.getElementById("myForm");
function doSomethingSmart() {
if(smartButton.value == "Edit booking") { // we gonna edit booking
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
smartButton.value = "submit"; // let it in disguise as submit button
}
else { // we gonna submit
if( isUserInputValied() ) {
myForm.submit(); // submiiiiiiiiiiiiiiiiiit !
// restore everything as if nothing happened
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
smartButton.value="Edit Booking";
}
else {
alert("please fill your form correctly!");
}
}
}
function isUserInputValid() {
// check whether the user input is valid
}
</script>
You need to prevent the default event if it's in edit mode so that it won't submit the form. You can always have your button type as submit no need to change it to button.
This should work:
var button = document.getElementById('editButton');
button.addEventListener('click', toggleButton);
function toggleButton(e){
var isEdit = button.value === 'Edit booking';
if(isEdit){
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
button.value = 'Submit';
e.preventDefault();
}
}

How to apply javascript to only 1 of 2 form submit buttons within 1 form?

Hi I'm using this script to prevent users from submitting specific blank form text input fields. Does a great job but I have 2 submit buttons within 1 form and I need this to work for only 1. Is there any way to make this code below apply to 1 specific button using the button id or name?
<script type="text/javascript">
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('[data-alert]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
</script>
Your first line:
$('form').on('submit', function () {
will take all form elements in the document. You can change the 'form' part of that to the ID of the form element i.e.
$('#form1').on('submit', function () {
You have one form and two submit buttons which, by default, will both submit the form. To prevent one button from submitting, add a click handler that both prevents the default submit action and does whatever else you want that button to do.
HTML
<form id="form1">
<input type="text" value="something" />
<input id="submit1" type="submit" value="send" />
<input id="submit2" type="submit" value="ignore" />
</form>
JavaScript
$('#submit2').on('click', function (event) {
event.preventDefault();
// Form will not be submitted
// Do whatever you need to do when this button is clicked
});
$('form ').on('submit ', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find(' [data - alert]').each(function (i) {
var thisInput = $(this);
if (!$.trim(thisInput.val())) {
thisAlert += '\n ' + thisInput.data('alert ');
canSubmit = false;
};
});
if (!canSubmit) {
alert(thisAlert);
return false;
}
});
Demo https://jsfiddle.net/BenjaminRay/ccuem4yy/

Categories

Resources