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()
Related
Okay, so I have a button inside a div. Here is that bit of HTML:
<div class="row">
<button type="button" id="submit">Send</button>
</div>
Before this button, there are other fields like name and email and stuff, and those are all inside a form, with the id "contactForm" (which is inside a div with class name "container").
I am making a JS file. I am trying to get it so that when the user puts in all the info like name & stuff, and hits submit, it will console.log() the name. That JS portion looks like this:
// Listen for submit btn click
document.getElementById('contactForm').addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
console.log(name);
};
Right, so this part looks fine to me, but then when I go into the localhost where the website is, and i put in whatever random stuff into the name, email and message fields, and i hit submit, nothing happens.
The debugger/console says
Uncaught TypeError: Cannot read property 'addEventListener' of null
On line 48, which is this:
document.getElementById('contactForm').addEventListener('submit', submitForm);
I started learning js today, so pretty new, but i cant find anything online that solves this problem. I found some that suggested i put the big JS portion inside a document.ready function, so it runs after everythings loaded. If I do that, which I tried, there is no error (like the line 48 one). It just doesnt say anything, and clicking on the btn doesnt do anything either (as in, doesnt show the name like i wanted).
Pls help, thanks.
If you want to use the "Submit" event, you have to made a form which have <input type="submit">, your button with the id'submit' is not a valid submit button.
For simple, if you want the function to be executed when your button is clicked, just use this:
document.getElementById('submit').addEventListener("click", function(){
e.preventDefault();
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
console.log(name);
});
You may be trying to attach an event even before the DOM has been loaded. You could use multiple solution for this.
Place your javascript code after the tag.
<form id='contactForm'></form>
<script>**** All your JavaScript goes here **** </script>
Place your code inside DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('contactForm').addEventListener('submit', submitForm);
});
have you checked your form's id for misspelling ?
also you can change a submit button to a simple div and add an onclick event handler instead if preventing default behavior. use it like this :
document.getElementById('submit').onclick=function(){document.getElementById('my-test-p').innerHTML='Submit was clicked'}
<button type="button" id="submit">Send</button>
<p id='my-test-p'></p>
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.
Firstly apologies if this is not a very good question, but I am not very familiar with Javascript at all. Secondly I did do research to find my problem I refer you to this post
I wrote this very basic function
function hideBtn(){
var btn = document.getElementById("submitBtn").style.cssText="display:none";
}
echo'<input type="submit" value="submit" name="submit" id="submitBtn" class="buttono" onclick="hideBtn()" />';
Which I want to hide my submit button after form is clicked as currently it is still displaying
Any help very much welcomed
Can it be that when the form is submitted the page is refreshed, and thus the function was not actually triggered?
Can it be that when the form is submitted the page is refreshed, and thus the function was not actually triggered?
Yes, that's very likely to be the issue. If you don't want the page refreshed, don't use a submit button, or submit the form to another window, or use an submit event handler on the form element and prevent the default action.
Separately: It's best not to completely replace all of the styles on the element. Instead, just set the specific style you want:
var btn = document.getElementById("submitBtn").style.display = "none";
The style property on elements is an object with properties for each of the CSS styles.
Since you are using submit button, you need to stop form from submitting and refresh page.
Second thing, you are not using styles correctly to hide the button.
function hideBtn() {
var btn = document.getElementById("submitBtn").style.display="none";
return false; // Prevent form from submitting
}
You probably want to write:
var btn = document.getElementById("submitBtn").style.display = "none";
See more: http://www.w3schools.com/jsref/dom_obj_style.asp
I am absolutly new in JQuery development and I have the following problem.
I have a form that contains this JQuery button:
<!-- RESET BUTTON: -->
<td>
<button class="resetButton" name="submitReset" onclick="return resetSearch(); return false;">Reset</button>
</td>
Clicking this button the user reset to null two input that are into my form performing this JavaScript function:
function resetSearch() {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
event.preventDefault();
}
The script is performed but the problem is that after that it go out from the previous function the form is submitted anyway and I don't want that this behavior happen.
How can I prevent that the form is submitted when the user click on the reset button? As you can see I also try to add this statment but it don't work:
event.preventDefault();
What am I missing? How can I fix this issue?
Another question is: is it the correct way to reset the values of the input tag of my form?
Give this a shot - you need to pass the event into the function. In addition, I've removed the need for inline JS.
$(".resetButton").click(function(e) {
var f = document.getElementById('dataDaAForm');
f.dataDa.value = null;
f.dataA.value = null;
e.preventDefault();
});
In addition to preventing the default, Javascript provides a method to reset your form:
$(".resetButton").click(function(e) {
document.getElementById("dataDaAForm").reset();
e.preventDefault();
});
Note: You tagged jquery, so I provided a jquery solution (although there is no jquery in your question).
The simplest way to create a reset button is an input type reset:
<input type="reset" value="Reset" />
Though if you really want to do it in javascript, the answer of James Hill will suffice
Try this
var form = $('#dataDaAForm')
$(".resetButton").on("click",function(e) {
form.reset()
e.preventDefault()
e.stopPropagation()
})
<input type="submit" name="btnADD" id="btnADD" value="ADD"/>
when user click add button twice, from get submitted twice with same data into table.
So Please help me to restrict user to submit from twice.
Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:
var $myForm = $("#my_form");
$myForm.submit(function(){
$myForm.submit(function(){
return false;
});
});
Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.
try out this code..
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
You can disable the button after clicking or hide it.
<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>
js :
function disableButton(button) {
button.disabled = true;
button.value = "submitting...."
button.form.submit();
}
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
And if you are not using any framework and looking for simple workout.
You can take help of the
java.util.UUID.randomUUID();
Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.
For your help i am writing some code snippet to give idea about how to achieve the thing.
<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:
$("#btnADD").on('click', function(btn) {
btn.disabled = true;
});
I made a solution based on rogueleaderr's answer:
jQuery('form').submit(function(){
jQuery(this).unbind('submit'); // unbind this submit handler first and ...
jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
return false;
});
console.log('submitting form'); // only for testing purposes
});
My solution for a similar issue was to create a separate, hidden, submit button. It works like so:
You click the first, visible button.
The first button is disabled.
The onclick causes the second submit button to be pressed.
The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>
I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.
You can use JavaScript.
Attach form.submit.disabled = true; to the onsubmit event of the form.
A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.
You can display successful message using a pop up with OK button when click OK redirect to somewhere else
Disable the Submit Button
$('#btnADD').attr('disabled','disabled');
or
$('#btnADD').attr('disabled','true');
When user click on submit button disable that button.
<form onSubmit="disable()"></form>
function disable()
{
document.getElementById('submitBtn').disabled = true;
//SUBMIT HERE
}
Create a class for the form, in my case I used: _submitlock
$(document).ready(function () {
$(document).on('submit', '._submitlock', function (event) {
// Check if the form has already been submitted
if (!$(this).hasClass('_submitted')) {
// Mark the form as submitted
$(this).addClass('_submitted');
// Update the attributes of the submit buttons
$(this).find('[type="submit"]').attr('disabled', 'disabled');
// Add classes required to visually change the state of the button
$(this).find('[type="submit"]').addClass("buttoninactive");
$(this).find('[type="submit"]').removeClass("buttonactive");
} else {
// Prevent the submit from occurring.
event.preventDefault();
}
});});
Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:
$(function(){
$(".button-disable-onsubmit").click(function(){
$(this).attr("disabled", "disabled");
$(this).closest("form").submit();
});
});
Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution.
Additionally you can even add another line to change the text value as well:
$(this).val("Sending, please wait.");
Add a class to the form when submitted, stopping a user double clicking/submitting
$('form[method=post]').each(function(){
$(this).submit(function(form_submission) {
if($(form_submission.target).attr('data-submitted')){
form_submission.preventDefault();
}else{
$(form_submission.target).attr('data-submitted', true);
}
});
});
You can add a class to your form and your submit button and use jquery:
$(function() {
// prevent the submit button to be pressed twice
$(".createForm").submit(function() {
$(this).find('.submit').attr('disabled', true);
$(this).find('.submit').text('Sending, please wait...');
});
})
None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.
var sending = 0;
$('#myForm').submit(function(){
if (sending == 0){
sending++;
// SUBMIT FORM
}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}
This only allows one submit in any one second interval.