Form is submitting when it shouldn't do - javascript

There is a problem with my jsfiddle application click here. When you open the fiddle then you will see a textarea, please follow steps below (in any borwser but IE):
1:Type in a question in the textarea
2: Click on the "AddQuestion" button. The question you have entered will be appended in the table below.
3: Delete all of the text in the textarea you have just added in the table below
4: Now click on the "Submit Details" button below.
Now as you can see it is trying to submit the details and go into a new page. This should not happen because I stated in my validation function that if a textarea which is appended in a table is empty or "", then display an alert stating "Please Enter in a Valid Question". Even if the question is valid, it should display a confirmation box stating if you want to proceed or not.
When the submit button is clicked it should follow the "myClickHandler" but why isn't it doing this?

Use event.preventDefault() to cancel the form submission.
BTW, you probably meant textAreaO.length, not textAreaO.value.length that throws TypeError.

plan a:
$("#addQuestionBtn").click(function(event) {
event.preventDefault();
...
});
plan b:
$('#enter').submit(function() {
....
return false;
});
add "return false;" in the end
quote:
http://api.jquery.com/submit/
The event handler can be bound to the form:
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. We can trigger the event manually when another element is clicked:

The textAreaO variable in the validate() function may contain more than 1 item from the selection. Iterate through each item and do the checking for each:
var isValid = true;
$(textAreaO).each(function() {
isValid = isValid && //insert your validation check here;
});
if(!isValid) alertValidation += "\nYou have not entered a valid Question\n";

Related

How to conditionally submit a form?

I am using following form and submit button in my dynamic html page.
<form method=\"post\" class=\"my-form\" >
and
<input type=\"submit\" name=\"submitButton\" value=\"Submit\" id=\"button1\" />
What I am trying to do is when a particular input is provided by user, then display an alert box asking if user wants to submit the change or just stay on the same page without submitting the change.
I can display the alert box (with help from stackoverflow members) but along with window.alert what I should add to JavaScript so the form is not submitted if user clicks "cancel" on window.confirm and the form is submitted if user clicks "ok" on window.confirm?
JavaScript example is at fiddle
$(document).on('input', '.my-input', function(){
$(this).closest('form').addClass('changed');
});
$(document).on('submit', '.my-form', function(e){
if($(this).hasClass('changed')){
var x=window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
if (x)
window.alert("Thresholds changed!")
else
window.alert("Thresholds not changed!")
}
$(this).removeClass('changed');
e.preventDefault();
});
You just need to change your logic so that preventDefault() is only called when the user declines the confirm box. Try this:
$(document).on('submit', '.my-form', function (e) {
if ($(this).hasClass('changed')) {
var allowSubmit = window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
if (!allowSubmit)
e.preventDefault()
}
});
Example fiddle
If you click 'OK' you'll see that the form is submit (and a warning from jsFiddle to use a POST request - but that's normal), whereas clicking 'Cancel' does nothing.
You can also return false in your submit function handler, it should work. Check this question for an example.

jQuery confirm button not in a popup confirm() dialog

I have a long form that I am validating with the jQuery validate plugin. After the form validates, I want the submit button to change into a confirm button with an appropriate message above about checking the form for errors. This button, when clicked again, should submit the form for real this time as long as all the required fields are still filled in.
I have the following:
var confirmed = function(){
alert($("#someForm").attr("name")); //just to see the function fire...
$("#someForm").submit();
return true;
}
$(document).ready(function(){
$("#someForm").validate({
submitHandler: function(form){
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
newBtn.click(confirmed)
newBtn.text("Confirm");
newBtn.insertBefore(oldBtn);
oldBtn.remove();
newBtn.attr({"id": "submit"});
}
});
});
...
<button type="submit" id="submit">Submit</button>
It works to validate the form, then the button changes text, the the function fires (the alert has the name of the form in it) when clicked, but the form never submits for real.
Any help or ideas would be greatly appreciated.
Thanks
EDIT:
Ok, I think I have figured it out. I have the submit button hidden and a button called Validate that just checks if the form is validated without submitting using $("#someForm").valid(); If it checks out, I hide the "Submit" button and show the "Confirm" button along with a little message about checking your submission, etc. See below:
$(document).ready(function(){
$("#submitBtn").hide();
$("#confMessage").hide();
$("#someForm").validate();
});
var checkValid = function(){
var isValid = $("#volunteer").valid();
if(isValid){
$("#validBtn").remove();
$("#submitBtn").show();
$("#confMessage").show();
}
}
...
<p id="confMessage">Please review your submission.</p>
<p><button id="validBtn" onclick="checkValid()">Validate</button>
<button type="submit" id="submitBtn">Submit</button></p>
Works perfectly, and is a heck of a lot cleaner than my original code!
remove oldBtn.remove(); then it will work.
You have
var oldBtn = $("#submit");
var newBtn = oldBtn.clone();
What above line doing is adding same DOM in html so that mean ID will be copied too.
And ID must be unique for each DOM.
Try to rewrite ID for cloned DOM and try.
AND
newBtn.click(confirmed)
This code means you are assigning event to newBtn not calling click event.
For call a click event use .trigger()

I am using appendChild in a 'contact; form to print a nice message upon submission, but the message disappears immediately

I'm making a very basic 'contact us' form, and I want to have a little "Thanks for your feedback" message appear on the page (not as an alert), upon successful form validation. The problem is, I hit the submit button, and the thankyou message appears for a split second and then disappears.
Code:
window.onload = init;
function init()
{
document.getElementById("contactForm").onsubmit=validate;
}
function validate()
{
//if statements to appear here returning false if any conditions are met
addMessage();
return true;
}
function addMessage()
{
var p = document.getElementById("content");
var l = document.createElement("p");
var m = document.createTextNode("Thanks for your message!");
l.appendChild(m);
p.appendChild(l);
}
What am I doing wrong? I am pretty new to javascript. Thanks!
You are returning true after calling addMessage(), so the message is displayed and then the form is submitted immediately.
If you want to prevent immediate form submission, you can either use standard alert() (it waits for user to press OK button) or prevent form submission by returning false and then submitting the form explicitly by calling form.submit() method when user clicks some button after he has read the message.
Actually, message like "Thanks for your message!" should be displayed on target page specified in action attribute of the form and loaded after form is already sent. It's not a good idea to say something that assumes the form is sent while it is not yet.
Both Firefox 15 and IE 9 update the DOM before submitting the form, so I can't see it's an issue. But anyhow, you can delay submission by calling it from setTimeout, that way it's pretty much guaranteed that the DOM will update to display the message, then the form will be submitted, e.g.
<script>
function validate(form) {
var formValid = false;
/* validatation stuff, set formValid to appropriate value, assume passed */
formValid = true;
if (formValid) {
// Show message
document.getElementById('message').style.display = '';
// Delay submit until after message displayed
setTimeout(function(){form.submit()}, 10);
// Stop form submitting immediately
return false;
} else {
/* form isn't valid, do whatever and cancel submission */
return false;
}
}
</script>
<span id="message" style="display: none">Success!!</span>
<form onsubmit="return validate(this);">
<input type="text" name="foo" value="bar">
<input type="submit">
</form>
Note that calling the form's submit method doesn't dispatch a sumbit event, so the submit handler isn't called again. This is contrary to the DOM 2 HTML standard, but browsers never followed it anyway.
It's been changed in the new "living" HTML specification so that a submit event must not be dispatched if submission is from the form's submit method.

return true or false based on button clicked in pop up window

Okay so with jQuery I've intercepted the .submit() of a form and I want to create a custom pop up window that shows them the data that the entered and asks them to confirm it. If they click the confirm button true is returned to .submit() and they continue but if false is pressed then they should not move on and have a chance to change their entry.
I already have the pop up window being made fine with the contents of the form being displayed and the buttons being shown. What I'm not sure how to do is bind the click functions of the buttons so that if one is clicked it returns false to .submit() and if the other is clicked true is returned to .submit()
If you need me to post some of my code just let me know.
I don't want to use a confirm dialogue since i would like it to be a custom pop up window.
You need to use a confirm() dialogue:
var submit = confirm('Are you sure?');
if (submit) {
$(this).submit();
}
else {
return false;
}
This works by the dialogue presenting the message "Are you sure?" to the user, if the user clicks on the confirmation ok button, the dialogue returns true to the variable submit, otherwise it returns false.
If false is returned (the user clicked cancel), then the if evaluates to false, and the else is executed.
You would need to pass the .submit() as a callback function to the dialogue. This isn't a one line solution but rather a pattern that you should get familiar with. This http://www.youtube.com/watch?v=hQVTIJBZook will probably be helpful for some of this topic along with other common issues that you may come across
Example:
function openPopup(form) {
//
// Put whatever code you use to open you
// popup here
//
// Bind click handler to submit form if they click confim
$("#id_of_confim_button").on("click", function() {
// Get the form that was
form.submit();
});
// Bind click handler for cancel button
$("#id_of_cancel_button").on("click", function() {
//
// Code to close your popup
//
});
};
$("#id_of_form_submit_button").on("click", function(event) {
// Stops the form from submitting
event.preventDefault();
// Get the form you want to submit
var form = $("#form_being_submit");
// Call your 'open custom popup' function and pass
// the form that should be submitted as an argument
openPopup(form);
});
Catching only this form's submits' click event won't handle all cases (f.ex. if someone hits enter on a non-textarea input, the form submits too).
If i want to handle submit in an asynchronous way, i used to fire manually submit after the original was prevented & bring in an isDirty state:
(function () {
var isDirty = true;
$("form#id").on("submit", function ( evt ) {
if (isDirty) {
evt.preventDefault();
popup( "... params ...", function () {
// this will called, when the popup ensures the form can be submitted
// ... & it will be called by the popup
isDirty = false;
$("form#id").submit();
} );
}
});
})();

test onclick in a function

Quick question: How do i check if a submit button is clicked in a function.
explained question:
ok, so I have a validate script for my sign-up page. The validate function is run onblur of every input (after the submit button has been clicked first).
However, the validate script not only gives the inputs a red background if the correct information hasn't been entered, but it also displays an alert message.
My problem is: I only want to display the alert message if the submit button is clicked, otherwise i just want to do change the background color. So how do I check if a submit buttons is clicked, in a function.
I could just have two different functions, one to be run for all the inputs. and one to be run for the submit button.
Register the submit event to your form to validate before it is submitted.
Added: You should register the function in document ready event.
$(function(){
$("#myformid").submit(function()
{ if(!highlightNshowError())//your function to validate the form, return false if validation failed
return false; //stop submitting the form
else
return true;
});
});
or simply
$(function(){
$("#myformid").submit(function()
{
return highlightNshowError();
});
});

Categories

Resources