Change form values after submit button pressed - javascript

[EDIT] After a lot of digging around, I found out that the problem was in how I integrated the CKEditor into my page. The simple and obvious way does work in this case, as laid out in the accepted answer.
Hi,
I need to change the values of a form, after the submit button has been pressed, but before the actual submission has taken place.
I've tried hooking into the "submit" event of the form, and changing the text field values there manually, but it looks like that doesn't actually change the values submitted.
Any ideas?

I'm curious about your statement that the submit handler didn't work for you. It does for me. I've used it for years to fill in hidden fields before sending forms in; should work for other form fields as well.
Example (live copy):
HTML:
<form id='theForm'
action='http://www.google.com/search'
method='GET' target='_new'>
<label>Search for:
<input type='text' name='q' id='txtSearch'></label>
<input type='submit' id='btnSearch' value='Search'>
JavaScript:
window.onload = function() {
document.getElementById('theForm').onsubmit = function() {
var txt = document.getElementById('txtSearch');
txt.value = "updated " + txt.value;
};
};​
Tested and working on IE6 and IE7 on Windows, and Chrome, Firefox, and Opera on Linux.
Update: Based on your comment below, you're using jQuery. Works fine using jQuery for everything as well:
$('#theForm').submit(function() {
var txt = $('#txtSearch');
txt.val("updated " + txt.val());
});
Live example Tested and working on the same set of browsers. This version uses a more open search rather than an id, and also still works.

You need to prevent the default submit action and then resubmit the form yourself manually:
$('form').submit(function(e) {
e.preventDefault();
// do your processing
this.submit(); // call the submit function on the element rather than
// the jQuery selection to avoid an infinite loop
});

Did you try adding function on click JavaScript event on the submit button and changing the values?
It may work because client script will execute first

You could use formData event.
The formdata event fires after the entry list representing the form's
data is constructed. This happens when the form is submitted, but can
also be triggered by the invocation of a FormData() constructor.
formElem.addEventListener('formdata', (e) => {
const formData = e.formData;
//no need change document.getElementById().value = "";
formData.set('field1', 'foo');
formData.set('field2', 'bar');
//updated formData
});

Related

Common jQuery to disable submit buttons on all forms after HTML5 validation

Please pardon me if it is a basic thing, because I am a new learner of Javascript/jQuery. I have been trying to disable submit button to disable multiple submits. I have come across multiple solutions here as well, but all those used specific form name. But I wanted to apply a global solution for all forms on all pages so I dont have to write code on each page, so I put this in footer, so all pages have:
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
This code works on all the forms in all pages as I wanted, but if there are HTML5 required fields in form and form is submitted without them, of course notifications are popped but button still gets disabled. So, I tried with this:
$('input:submit').click(function(){
if ($(this).valid()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
But this does not work. Kindly help me so that jQuery only disables when all HTML5 validation is done. Thanks
Try this and let me know:
$('input:submit').click(function(){
if ($(this).closest("form").checkValidity()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
Ruprit, thank you for the tip. Your example did not work for me (in Firefox), but it helped me a lot.
Here is my working solution:
$(document).on("click", ".disable-after-click", function() {
var $this = $(this);
if ($this.closest("form")[0].checkValidity()) {
$this.attr("disabled", true);
$this.text("Saving...");
}
});
Since checkValidity() is not a jQuery function but a JavaScript function, you need to access the JavaScript element, not the jQuery object. That's the reason why there has to be [0] behind $this.closest("form").
With this code you only need to add a class="disable-after-click" to the button, input, link or whatever you need...
It is better to attach a handler to the submit event rather than a click event, because the submit event is only fired after validation is successful. (This saves you from having to check validity yourself.)
But note that if a submit button is disabled then any value they may hold is NOT submitted to the server. So we need to disable the inputs after form submission.
The question is compounded by the new HTML5 attribute form which allows associated inputs to be anywhere on the page as long as their form attribute matches a form ID.
This is the JQuery snippet that I use:
$(document).ready( function() {
$("form").on("submit", function(event) {
var $target = $(event.target);
var formId = $target.attr("id");
// let the submit values get submitted before we disable them
window.setTimeout(function() {
// disable all submits inside the form
$target.find("[type=submit]").prop("disabled", true);
// disable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", true);
}, 2); // 2ms
});
});
---[ WARNING ]---
While disabling submit buttons prevents multiple form submissions, the buttons have the unfortunate side effect of staying disabled should the user click the [Back] button.
Think about this scenario, the user edits some text, clicks submit (and get redirected to different page to view the edits), clicks back to edit some more, ... and ... they can't re-submit!
The solution is to (re-)enable the submit button on page load:
// re-enable the submit buttons should the user click back after a "Save & View"
$(document).ready( function() {
$("form").each(function() {
var $target = $(this);
var formId = $target.attr("id");
// enable all submits inside the form
$target.find("[type=submit]").prop("disabled", false);
// enable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", false);
});
});
Try this
`jQuery('input[type=submit]').click(function(){ return true;jQuery(this).prop('disabled','disabled');})`
run this code on successful validation of the form

How to not validate form on reset()?

I'm using
$('#myform')[0].reset();
to clear HTML form fields when a clear button is clicked. I'm also using jquery.validate.js. So when the above runs, it triggers form validation. All form fields with any validation then display their error messages. How do I prevent this?
I have tried this but it didn't do anything:
$('#myform').removeAttr("nonvalidate");
From the question you linked, the answer is what you want... All you have to do is capture the reset event and call v.resetForm().
var v = $('form').validate(); //etc etc whatever you have here, the important part is saving "v"
$('form').on('reset',function () {
v.resetForm();
});
See it working here: http://jsfiddle.net/uuu8jerr/

How to prevent submitting form based on text in an html element?

I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}

Adding hidden field in beforeunload

On my page I'm using a form which on submit should get some extra hidden fields. The problem however is that I can't know the name/id of the form nor the submit button so I can't use functions like onClick etc. Therefore I'm using the beforeunload event to trigger an event when the user tries to leave the page (this includes submitting a form). I'm using the document.activeElement to find out what triggered the event and if it's a form/submit I'm adding the hidden fields to the form.
Stripping down the code it comes down to something like this:
var javascriptData = ['val1','val2','val3']; // usually gets values dynamically and can differ in size
$(window).bind('beforeunload', function(e) {
var activeForm = document.activeElement.form;
for(var i = 0; i < javascriptData.length; i++){
$(activeForm).append('<input type="hidden" name="test-data[]" value="'+javascriptData[i]+'" />');
}
return false; // just for debug purposes.
}
The code works and the element is added to the form but it doesn't show up in the $_POST on the next page. However, the final line of code (return false) creates a pop-up asking if I want to leave the page, if I stay on the page, press the submit button again and then leave the page and check $_POST, the field there. My guess is that the data for the $_POST is collected before the beforeunload function is triggered.
My question is: "Is there a way around this so I can add a hidden field to a form in the beforeunload event?".
Help is much appreciated, thanks in advance.
Why not add it to all forms on the page?
$(document).ready(function() {
$("form").append('<input type="hidden" name="test-data[]" value="test" />');
});
Like the comments above mentioned, you can just hook onto the submit event.
$('form').submit(function() {
for(var i = 0; i < javascriptData.length; i++){
$(this).append('<input type="hidden" name="test-data[]" value="'+javascriptData[i]+'" />');
}
}

jQuery form submit: Any way to know what element triggered the submit?

I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.
$('form').submit(function() {
...code done here to validate form fields
});
The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?
I asked this same question: How can I get the button that caused the submit from the form submit event?
The only cross-browser solution I could come up with was this:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.
well this will only fire if the type of the input button is like so:
<input type='submit' ...
so make sure the cancel button does not have type='submit' and it should work
EDIT
This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.
#Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:
$('form').submit(function(e){
if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
//don't validate
}
else{
//validate
}
});
var myForm = $('form');
$('input[type="submit"]',myForm).click(function(e) {
var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
//do other things here
});
EDIT
.submit(function(event){
var target = event.originalEvent.explicitOriginalTarget.value;
//But IE does not have the "explicitOriginalTarget" property
});

Categories