Assign JavaScript function to submit button, which should execute conditionally - javascript

I have a simple form with one hidden input field, and a submit button. When the user clicks the submit button, I want it first to run a JavaScript function with a confirm() function. Depending on whether the user hits 'Ok' or 'Cancel', I want the form to submit, or to not submit.
How do I successfully assign an on-click function to a submit button, and have it work as described above?
function confirmDelete() {
var del = confirm("Are you sure you wish to delete this post?");
if (del)
//continue and submit the form
else
//the form should not be submitted
}
Here is the form:
<form action="/delete/" method="post">
<input type="hidden" name="path" value="'.$path.'" />
</form>
I realize that I could scrap the form altogether and just pass the hidden variable as a GET variable to the /delete/ page, however I would prefer to use a POST variable for security reasons.

This would suffice:
<input type="submit" value="Delete" onClick="return confirm('Are you sure?');" />

Related

Form validation executing incorrectly

My script disables the submit button for a form if the text-input is empty. I wrote a separate script that prompts a confirmation window before the user is allowed to submit updated content into the database. Both scripts work fine individually.
My problem arises when I try to combine both scripts using an if/else statement. The code below disables the button as expected and inserts the user-inputted data into the database once the submit button is enabled, however the confirmation window is entirely bypassed.
How can I get the confirmation window to appear again before anything is submitted?
JavaScript:
<script>
function validationCheck() {
if(document.getElementById('updateEventTitle').value==='') {
document.getElementById('updateBtn').disabled = true;
} else {
document.getElementById('updateBtn').disabled = false;
//Confirmation window
function updateEvent() {
var r =confirm('Do you want to update this item?');
if (r==true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
</script>
HTML:
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' onkeyup='validationCheck()' required/>
<input class='btn btn-primary btn-sm' onclick='updateEvent()' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled/>
</form>
You make reference to event in your two functions, but neither of them declared the event function argument. You need to set up the event argument in your functions:
function validationCheck(event)
function updateEvent(event)....
And, just nesting a function inside of another doesn't make the second one run. Instead, reorganize things a bit and don't set up your events with inline HTML event attributes, like onclick in the first place. Do your JavaScript work separate from your HTML.
Also, with a form, it's not the click event of the submit button that you should be handling, it's the submit event of the form.
Also (FYI), don't bother with self-terminating HTML tags.
Lastly, you've got your form action set to: editevent.php?updaterow=$iddata but later, if the user confirms that they want to submit, you are redirecting to: server.php. While that redirect will now work, the data that was inputted into the form will not be sent to it. Instead, with form validation, you simply test for situations where the submit should be halted and if that scenario doesn't exist, you simply do nothing and let the form submit as it was going to.
// Set up your event handlers in JavaScript, not with inline HTML
document.querySelector("form").addEventListener("submit", validationCheck);
document.getElementById("updateEventTitle").addEventListener("keyup", validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
if(eventTitle.value==='') {
btnUpdate.disabled = true;
} else {
btnUpdate.disabled = false;
// If it was the submit button that was pressed...
if(event.type === "submit"){
// Confirmation window
// You only need to test for and handle situations where the form
// submit event should be halted. Otherwise, let the form submit to its action URL
if (!confirm('Do you want to update this item?') {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
Is there a way to use #Scott Marcus method for multiple seperate forms on the same page, for example if I had a second additional form such as below? Javascript only seems to allow you to pass one param at a time using .getElementById
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>

How to Hide a button on one page and show that button on different page?

I have two buttons of type="submit" one for submitting to the database and other for updating the database and for the same purpose I got two PHP files one for submitting and other for updating.
The problem is that I want to hide update button on fist.php and show the submit button and vice-versa.
Let's say the page, which has the two buttons you mentioned, send a request to query existing record.
If no record found, the page is supposed to submit to "submit" page, else to "update" page.
Then, in your code, you can put a hidden input element, which contains the value, by which you know where to submit.
maybe something like this:
<input type="text" id="direction" value="" display="hidden">
Then, you have a button, not a type=submit, but a type=button.
something like this:
<input type="button" id="submitBtn" value="submit" onclick="submitForm()">
Then you have a javascript function. something like this:
<script language="javascript">
function submitForm(){
if(document.getElementById("direction").value=="submit"){
//Change form1 to your real form name.
document.form1.action="submit.php";
document.form1.submit();
}else if(document.getElementById("direction").value=="update"){
//Change form1 to your real form name.
document.form1.action="update.php";
document.form1.submit();
}else{
alert("error happened. the direction unknown, unable to submit the form");
}
}
</script>

How add name input submit() jQuery

I have a JavaScript that changes the attribute of the input button to "disabled", so the user don't submit the page twice.
// Disables multiple submit
function disableSubmit (btn, submitForm) {
// Sets button as disabled, changes class and cursor
$(btn).attr("disabled", true);
$(btn).toggleClass("disabled alt2");
$(btn).css('cursor', 'initial');
$(btn).attr("value", "Sender...");
// Submits form
$(submitForm).submit();
}
// Disables submit for order form
$("#send-order").click(function () {
return disableSubmit(this, "#order");
});
The problem is that I need to track the name of the button submitting the page so I can handle it in my Django view.py file.
HTML
<input value="Send bestilling" id="foo" name="send-order" type="submit" class="button alt2">
View.py
request.POST.get("send-order", False)
But if I use my script to submit the page, I can't get the name of the input submitting the page. Is there any way to set a name for the button submitting the page in my script?
I tried this but didn't work:
$(submitForm).submit().attr("name", "send-order");
Solution
I had to change the code inside views.py in order to make this work.
you can use preventdefault or return false
$("#send-order").click(function (event) {
event.preventDefault();
return disableSubmit(this, "#order");
});
Or
<input id="send-order" value="Send" type="submit" onclick="disableSubmit(this, '#order');return false" />
One way you can do this is by creating a hidden input on your form, with a name of its own. Something like below.
<input type="hidden" name="buttonName" id="buttonName" />
Then, in your disableSubmit function, make it set the value of that input before submitting.
$(submitForm)
.find("input[name=buttonName]")
.attr("value",
$(btn).attr("name")
);
From there, you can just retrieve the "buttonName" value in your View.py.

send <form> information through 2 different Submit buttons, that calls the same function but need to know from which submit button came the call

I'm sending information through 2 different Submit buttons, that calls the same function but I need to know from which submit button came the call.
I have a form with 'x' parameters that I'm going to send to a js function thats going to validate the data. After I validate the data I need to send that data to diferent js function depending on the submit button press
my form is like this:
<form name="Datos_ConfiguracionRangos_Tension_Laboral" action="#" onsubmit="Consultar_ConfiguracionRangos('Tension', 'Laboral'); return false" method="post">
<button id="button" type="submit" name="graficar" value ="graficar">Graficar</button>
<button id="button2" type="submit" name="guardar" value ="guardar"> Guardar Configuraciones</button>
</form>`
One way would be to allow your script to submit the form, and use regular buttons.
<button id="button" onclick="validateMe(this)" value ="graficar">Graficar</button>
...then in your function:
function validateMe(e) {
alert(e.value) <-- this tells you which button was presssed.
.... your validation code ...
document.forms.Datos_ConfiguracionRangos_Tension_Laboral.submit();
}

JSP: two submit button on the same form

I have two submit buttons on the same form in JSP page, one of each appear in the form depending on the case.
The problem is that one of the submit buttons submit the form, and the other does not .
here's the HTML form
<form name="stdActivationForm" id="stdActivationForm" action="ParentManagementServlet" method="post" onsubmit="return validateStudentActivationForm()">
<input class="${isActivated? 'hideDiv':'showDiv'}" type="submit" value="confirm" name="submit" onclick="submitForm('add')"/>
<input class="${parent != null? 'showDiv':'hideDiv'}" type="submit" value="update" name="submit" onclick="submitForm('update')"/>
</form>
and here's the javascript function
function submitForm(btnName)
{
var form = document.getElementById("stdActivationForm");
if (btnName =='add')
document.form.submit();
else if(btnName =='update')
document.form.submit();
}
I think your JavaScript function needs to return true.
Alternatively you can just remove the onclick reference and it should work with just type="submit".
Good luck.
Get rid of the onclick. You don't need it here. The type="submit" already submits the form. Your concrete problem is likely caused because the onsubmit of the <form> has returned false.
Try changing the input type of the buttons to "button" and the method to:
function submitForm(btnName)
{
// skip validation for updates, remove btnName =='add' && when it is working
if (btnName =='add' && !validateStudentActivationForm())
{
return;
}
document.forms["stdActivationForm"].submit();
}
Both buttons are currently submitting to the same Servlet anyway.

Categories

Resources