Make on submit event wait for user input? JS - javascript

To make it clearer.
JavaScript.
I need to replicate the behaviour of a confirm() but without using a confirm() xd.
So basically, i have to stop the submit and wait for a true/false value from the user and the submit the form.
Now i´m preventing the form submit and then when the user click "yes" force the submit again with a .submit().
But i don´t know if is there any way to keep the on submit event waiting for a true or false return from another function.
Thank you.
Edit: I´ve just realized i can´t do a .submit() cause it will launch the onsubmit even again.

With confirm():
document.getElementById('submit-button').onclick = function() {
if(confirm('Are you sure you want to submit?')) {
// Do something
}
// Don't do something
}
<body>
<input type="text" name="input" />
<button id="submit-button" type="submit">Submit</button>
</body>
Without confirm():
var submit = document.getElementById('submit-button');
var confirm = document.getElementById('confirm-button');
var cancel = document.getElementById('cancel-button');
document.getElementById('submit-button').onclick = function() {
submit.style.display = 'none';
confirm.style.display = 'inline';
cancel.style.display = 'inline';
}
document.getElementById('confirm-button').onclick = function() {
// Submit form
}
document.getElementById('cancel-button').onclick = function() {
submit.style.display = 'inline';
confirm.style.display = 'none';
cancel.style.display = 'none';
}
<body>
<input type="text" name="input" />
<button id="submit-button" type="submit">Submit</button>
<button id="confirm-button" type="submit" style="display: none;">Confirm</button>
<button id="cancel-button" type="submit" style="display: none;">Cancel</button>
</body>

Related

Delay Button Submit Javascript

I'm trying to add adelay on my submit button in javascript.
But it just seems to freeze and no longer commits any action after clicking on it.
Does anyone have an explanation ?
function Progress() {
var button = document.getElementById("Button");
var form = document.getElementById("new_video")
form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
form.submit();
}, 2000);
return false;
}
}
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" onclick="Progress()" id="Button" data-disable-with="Upload" disabled="">
// Cache your Form Elements
const EL_form = document.querySelector("#myForm");
const EL_formSubmitBtn = EL_form.querySelector("#Button");
const Progress = (evt) => {
evt.preventDefault(); // Prevent Browser Submit action
EL_formSubmitBtn.disabled = true; // Disable the submit button
setTimeout(function() {
EL_form.submit(); // Or do AJAX stuff here
EL_formSubmitBtn.disabled = false; // Enable the submit button
}, 2000);
};
// Use Element.addEventListener instead of inline JS
// Don't attach handlers to button, rather use the Form "submit" Event:
EL_form.addEventListener("submit", Progress);
<form id="myForm" action="demo.php">
<input id="Button" type="submit" value="Upload" class="btn btn btn-primary">
</form>
PS: Don't capitalise names of regular functions that do not actually return an Object - or are not a Class by definition, use rather progress as your function name. Or rather be more descriptive, it's actually a formSubmitHandler
You could try this:
var button = document.getElementById("Button");
var form = document.getElementById("new_video");
button.onclick = function(event) {
event.preventDefault();
setTimeout(form.submit, 2000);
}
and
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" id="Button" data-disable-with="Upload">
Hope this helps.

Double submit, prevent default not working

I hope someone can help me.
I have two buttons on my page in my form. "Save" and "Publish". This is the HTML:
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum({{ album.id }}, '{{ album.title }}')">Publish</button>
The first one saves the album, the second one sends an e-mail to the owner. The second one ("Publish") needs to trigger a confirm first ("Are you sure?"). When you click "Ok", the form should submit, but if you click "Cancel" (in the confirm box), it should do nothing.
Here is my JS:
function publishAlbum(album_id, album_title)
{
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
}
I tried literally everything (prevent default, return etc), but every time I click "Cancel", the form still submits and the e-mail is sent.
Can someone help me?
Publish
$('.publish-button').on('click',function(e){
e.preventDefault();
let albumId = $('#selectYourAlbumId');
let albumTitle = $('#selectYourAlbumTitle');
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
// POST your form through an AJAX call
})
You need to get the event object somehow (e.g. by adding an event listener to the button). Then you are able to prevent the form submission, like so:
const album = {
id: 1,
title: 'Test',
};
document.querySelector('[name=publish]').addEventListener('click', function(e) {
if (!publishAlbum(album.id, album.title)) {
e.preventDefault();
}
});
function publishAlbum(album_id, album_title) {
var result = confirm('Are you sure you want to publish this album?');
if (!result) {
return false;
}
// do your stuff
return true;
}
<form action="https://example.org" method="POST">
<button type="submit" class="button">Save</button>
<input type="submit" class="button" name="publish" value="Publish" />
</form>
Assuming you have these buttons inside a form tag, you can try this:
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum()" id="myButton">Publish</button>
<script>
function publishAlbum() {
var txt;
if (confirm("Press a button!") == true) {
$("#myButton").trigger('submit');
} else {
txt = "You pressed Cancel!";
alert(txt)
}
}
</script>
</body>
</html>
I used this:
$(document).ready(function() {
$('#form-publish .button-publish').on("click", function(e) {
var c = confirm("Are you sure?");
if (c) {
return;
} else {
e.preventDefault();
}
});
});

HTML Form - successfully post form but do not leave the page (NO-JQUERY)

I have a simple form inside a Pop up window. In my form I have only one checkbox with a label for the checkbox. What I have done is when the user clicks on the label or checkbox, the submit button to appear and the user will be able to submit the form. Moreover, I would like when the user press the submit button to collect the information in my database and then to close the pop up window and continue on the website normally without leaving. I am not sure how to achieve that but this is what I have done until now. Please I need some help to achieve this.
1) I want to submit the form successfully and collect the information to my database.
2) I want to close the PopUp Window.
3) I do not want to leave the page.
Thanks.
HTML:
<div id="popUp">
<form id="myform" method="post" action="somepage.php" onsubmit="return closeWindow">
<input type="checkbox" id="checkbox" name="checkbox"><label for="checkbox">Click to show Submit</label><br>
<input type="submit" id="submit-button" value="Submit" style="display:none">
</form>
</div>
CSS:
#popUp {
height:400px;
border:1px solid #000;
background:#e2e2e2;
}
JS:
var checkBox = document.getElementById("checkbox");
var submitButton = document.getElementById("submit-button");
var PopUpWindow = document.getElementById("popUp");
function checboxFunc() {
if (checkBox.checked) {
submitButton.style.display = "block";
} else {
submitButton.style.display = "none";
}
}
checkBox.addEventListener("click", checboxFunc);
function closeWindow() {
PopUpWindow.style.display = "none";
return false;
}
submitButton.addEventListener("click", closeWindow);
Although you could use AJAX, a simpler approach would be to put the form in another HTML file and load it into an iframe and set the form's target="name_of_iframe".
You will also have to get rid of the onsubmit attribute and instead add an event listener. Like so.
yourpage.html
<iframe id="popUp" name="popup" src="path/to/form.html"></iframe>
form.html
<form id="myform" method="post" action="somepage.php" target="popup">
<input type="checkbox" id="checkbox" name="checkbox"><label for="checkbox">Click to show Submit</label><br>
<input type="submit" id="submit-button" value="Submit" style="display:none">
</form>
yourpage.js
var checkBox = document.getElementById("checkbox");
var submitButton = document.getElementById("submit-button");
var PopUpWindow = document.getElementById("popUp");
var form = document.getElementById("myform");
function checboxFunc() {
if (checkBox.checked) {
submitButton.style.display = "block";
} else {
submitButton.style.display = "none";
}
}
checkBox.addEventListener("click", checboxFunc);
function closeWindow() {
PopUpWindow.style.display = "none";
return false;
}
form.addEventListener("submit", closeWindow);
When this is submitted, the somepage.php will load, but only inside the popup, wich will be hidden anyway. So you will have the desired effect.
Ajax was invented to solve this. Jquery wraps it nicely like:
checkout $.post
Two suggestions, if you are doing this type of request, dont complicate matters and use the FORM tag, just use the inputs.
Secondly send JSON instead of form data, can be messy trying to get in the correct format.
So your client side would look something like this:
var req_obj = {
"id":"ENTER_DATA",
"params":{
"param_name1":"param_val1",
"param_name2":"param_val2"
}
};
$.post(
APP.ActionUrl,
JSON.stringify(req_obj),
function(data){ //this is the callback,do your confirmation msg },
"json");
SERVER:
$req_obj = json_decode(get_post_data());
$param1 = $req_obj->params->param_name1;
function get_post_data(){
$buf = '';
if(($h_post = fopen('php://input','r'))){
while(!feof($h_post))
$buf .= fread($h_post,1024);
fclose($h_post);
return $buf;
}
else
return false;
}

Cancel on confirm still submits form

I have a form with a submit and cancel button and I want to show a different confirm message bepending on which button is clicked so this is what I've come up with.
function confirmDialog(buttonId) {
switch (buttonId) {
case "cancel":
var result = confirm("cancel message");
submitForm(result);
break;
case "submit":
var result = confirm("Submit message");
submitForm(result);
break;
}
};
And my submitForm function looks like
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
Now my issue is that when I click cancel the form still gets submited. Can someone tell me what I'm doing wrong please. I have return false; in my else condition so I really don't know why it still submits the forms.
I've looked at the following questions but I'm still facing the issue
jQuery Still Submits Ajax Post Even When “Cancel” is clicked on Confirm Dialog
javascript confirm (cancel) still submits form when returning false
Edit: Cancel button html as requested
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
Further Edit
I call the confirmDialog function in the click event the appropriate button as follows:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId)
});
your button have default behavior of submit
replace
<button type="submit" id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
with
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
... Edit after your update Try this code ....
replace your code
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
return false;
}
};
with
function submitForm(result) {
console.log(result); //this is false when I click cancel in the confirm box
if (result && $("#myform").valid()) {
$("#myform").submit();
}
else {
const element = document.querySelector('myform');
element.addEventListener('submit', event => {
event.preventDefault();
console.log('Form submission cancelled.');
});
}
};
----- Alternative working code if you consider changing your HTML structure ---
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
</head>
<body>
<form id="MyForm">
<button id="btnSubmit" class="btn btn-primary">Submit</button>
<button id="btnCancel" class="btn btn-danger">Cancel</button>
</form>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
$('#MyForm').submit();
});
$("#btnCancel").click(function (e) {
e.preventDefault();
var result = confirm("Sure Cancel?");
if (result) {
const element = document.querySelector('#MyForm');
element.addEventListener('submit', function (e) {
e.preventDefault();
});
alert("Form Submission Canceled");
}
else {
$("#MyForm").submit();
alert("Form Submitted");
}
});
})
</script>
</body>
</html>
Your <button> tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just <button id="cancel".... />
<button id="cancel" class="btn btn-danger btn-block" value="Cancel">Cancel</button>
This will resolve your issue. Hope this helps!
The form submit is only omitted when "onsubmit" gets "false" from the Javascript handler.
Try this
"return submitForm..." (instead of just "submitForm...")
(2. Remove semicolons after function's closing brackets)
Update
Maybe the problem is the combination of input type=submit and $("#myform").submit();
If <form onsubmit=... receives no false (for example from a function return), the form will be submitted.
If <input type=submit onclick=... receives no false (for example from a function return), the button action (form submission) will be performed.
Raw (unchecked) solution option without using input type=submit:
HTML
<form id="myform" onsubmit="formValidation()">
<button value="Submit" onclick="buttonHandler(true)">
<button value="Cancel" onclick="buttonHandler(false)">
</form>
JS
function formValidation()
{
return $("#myform").valid();
}
function buttonHandler(isSubmit)
{
if (isSubmit ==== true)
{
if (confirm(submitMessage) === true)
{
$("#myform").submit();
}
}
else
{
if (confirm(cancelMessage) === true)
{
$("#myform").submit();
}
}
}
You can get this to work if you use an input tag instead of button tag and retain your styles by keeping your classes. e.g.
<input id="SomeId"
class="btn btn-danger btn-block"
onclick="return confirm('Are you sure you want to delete: X');"
value="Delete" />
I had similar problem and solved it with click event, which is very similar to your problem.
Try this:
$("#cancel").click(function () {
var buttonId = $(this).attr("id");
confirmDialog(buttonId);
return false;
});
Hope it helps.
Your tag's type attribute seems to have submit as its value, just remove the type="submit" attribute in your HTML code and keep it just
<button id="cancel".... />

Validation on input field using javascript

I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}

Categories