In jQuery, if I assign class=auto_submit_form to a form, it will be submitted whenever any element is changed, with the following code:
/* automatically submit if any element in the form changes */
$(function() {
$(".auto_submit_form").change(function() {
this.submit();
});
});
However, if I want to the form to submit only when specified elements are changed:
/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
$(".auto_submit_item").change(function() {
$(this).parents().filter("form").submit();
});
});
I'm just learning jQuery. Is there a better way to do this?
/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
$(".auto_submit_item").change(function() {
$("form").submit();
});
});
Assumes you only have one form on the page. If not, you'll need to do select the form that is an ancestor of the current element using $(this).parents("form").submit()
You can use an expression in the parents() method to filter the parents. Hence this might be a little more efficient:
/* submit if elements of class=auto_submit_item in the form changes */
$(".auto_submit_item").change(function() {
$(this).parents("form").submit();
});
I would give an id to the form:
$(".auto-submit-item").change(function() {
$("form#auto-submit").submit();
});
I came up with a generic approach to this:
$('.autoSubmit, .autoSubmit select, .autoSubmit input, .autoSubmit textarea').change(function () {
const el = $(this);
let form;
if (el.is('form')) { form = el; }
else { form = el.closest('form'); }
form.submit();
});
All elements of a form:
<form class="autoSubmit">
<select><option>1</option><option>2</option></select>
</form>
Only individual elements
<form>
<select class="autoSubmit"><option>1</option><option>2</option></select>
</form>
Related
I have varied textareas in a form that I wish to be completed before the submit button is activated. I have researched into this and already found how to specify particular textareas/inputs however dependent on the user group will be dependent on how many text areas are shown so I need a blanket javascript to just check that any textareas shown on the page are filled before the submit button is activated.
I have looked at this: http://jsfiddle.net/qKG5F/641/ however have not managed to successfully implement it myself.
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
Could this be because of how I have created my textareas? As shown below
<textarea name="i_2" id="i_2" class="input-block-level"></textarea>
Instead of using <input> as the JSFiddle example does above.
Is there any way to disable the submit button if not all textareas have been filled (without specifying each textarea)? I have edited my submit button accordingly with the JSFiddle example.
In HTML5 you can actually use a very simple "required" command to make any form elements a required field before the submit button is activated. It removes the need for any unnecessary JavaScript.
<textarea name="i_2" id="i_2" class="input-block-level" required></textarea>
give it a try :) stuff like this is why I love HTML5
Why do you think that textarea is an input? Here is the code for the situation when you have inputs and textareas in one form, and you want the button to be disabled if one of the inputs or textareas is empty. Input and textarea are different html elements! You can't select textarea with "input".
(function() {
$('form > input, form > textarea').keyup(function() {
var empty = false;
$('form > input, form > textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
For only textareas use:
$('form > textarea')
Better approach is to use class name, for example "must_be_filled" and assign this class to any html element.
The you can select elements by:
$('form > .must_be_filled')
Try this:
http://jsfiddle.net/g0m79p81/
I have a hidden input field like this in jade:
input(name='saintForm[quotes][]', type='hidden')
I want to use jquery to add to this array from a dynamic unordered list, but not sure how. Here's my failing attempt:
$('#form').on('submit', function(e){
e.preventDefault();
$('.quote').each(function (i){
var item = $(this).text().replace(' (x)','');
$("input[name='saintForm[quotes][]']").push(item);
});
this.submit();
});
If you're just adding a value to the default form functionality you could create an input with a value.
// grab your form and wrap it in jQuery
var myForm = $('#form');
// list teo the submit event
myForm.on('submit', function(e) {
e.preventDefault();
$('li.quote').each(function() {
$('<input />', {
type: 'text', // input type
name: 'saintForm[quotes][]', // the name of the form input
value: $(this).text() // the text from the current list-item
}).appendTo(myForm); // append each input to the form
});
myForm.submit(); // submit the form
});
You can of course send all sorts of arbitrary data to the server easily with AJAX but if you are just using the normal form submit I guess this is a good way to do it.
I have a form with multiple divs with same names (full-width). They all are on the same level. One of them is hidden (with a class hide). What I want is that if I select Submit, it should not submit, first hide all the brother divs of the hidden div (in this case full-width) and unhide the one with the class hide.
Now when I press again, it should just submit the Form.
JSFiddle is here:- http://jsfiddle.net/xmqvx/2/
Your code had a couple issues:
You used event.preventDefault but passed event in as e - should be e.preventDefault
Your ID selector targeted an ID that didnt exist (changed to #submit-this)
The working code:
$("#submit-this").click(function (e) {
e.preventDefault();
if ($(".full-width").hasClass("hide")) {
$(".full-width").hide();
$(".full-width.hide").removeClass("hide").show();
} else {
alert("Submitting");
$("#this-form").submit();
}
});
http://jsfiddle.net/xmqvx/4/
You could also take advantage of JavaScript's closures like so, to avoid having your behavior be dependent on your UI:
$(document).ready(function () {
var alreadyClicked = false;
$("#submit-this").click(function (e) {
e.preventDefault();
if (alreadyClicked) {
$('#this-form').submit();
} else {
$('.full-width').hide();
$('.hide').show();
alreadyClicked = true;
}
});
});
In my VB.NET project, I have a UI with some text input fields and a save/submit button. I want the save button to be in a disabled state on page load, and remain that way until a change is made to one of the inputs. And the save button should get disabled again if the values entered by the user are the same as they were at page load. So basically, the save button should be enabled only when there is an actual change.
How can I do this using jquery?
$(':input').change(
function(){
$("#submitButtonId").prop("disabled",false);
}
);
since you said it is dynamic, use on.
$(document).on("change", ":input",
function(){
$("#submitButtonId").prop("disabled",false);
}
);
You can handle that in the change event
$('input[type="text"]').on('change', function() {
// Change event fired..
$('input[type="submit"]').prop('disabled', false);
});
//This will bind all existing and dynamically added selects onChange to the handler
$(document).on('change', function(e) {
onChangeHandler();
}
// handle the event
function onChangeHandler() {
if (checkValues()) {
$('#yourButtonId').prop("disabled", false);
}
else {
$('#yourButtonId').prop("disabled", true);
}
}
// check all values against originals - data-* attributes are a good way to store data on
// an element. So have you can have:
<select id="id1" data-originalvalue="myValue"></select>
// compare the current value to the original value - if any one of them differ, return
// true
function checkValues() {
$.each($('select[data-originalvalue]'), function() {
if ($(this).val() !== $(this).attr(data-originalvalue){
return true;
}
return false;
});
}
After clicking an html reset button,
<input type="reset" />
I would like to execute some code. How can I do this and ensure that the form was reset prior to doing so?
I don't particularly like the idea of binding the reset event to the reset button instead of the form. A form can be reset by other means and in those cases your event will not trigger.
Instead, bind the function to the reset event but place it within an instantaneous setTimeout. It will ensure the form is actually reset prior to calling the function.
$('form').on('reset', function(e)
{
setTimeout(function() { /* ... */ });
});
Using a setTimeout as Ben does here is best: https://stackoverflow.com/a/21641295/144665
$("input[type='text']").val('Hello Everybody!');
$("input[type='reset']").closest('form').on('reset', function(event) {
// executes before the form has been reset
console.log('before reset: ' + $("input[type='text']").val());
setTimeout(function() {
// executes after the form has been reset
console.log('after reset: ' + $("input[type='text']").val());
}, 1);
});
You might want to narrow that form selector down to the specific form involved, maybe with an id.
Fiddle Proof: http://jsfiddle.net/iambriansreed/Zh5cd/
Update: use preventDefault instead of return false.
$('input[type="reset"]').click(function(evt) {
// Prevent the reset button from firing the form's reset event again
evt.preventDefault();
$(this).closest('form').get(0).reset();
// At this point your form's inputs should have their values reset
});
http://jsfiddle.net/EYqrX/1/
The suggestion is that instead of using <input type='Reset'> use <input type = "button"> in this way you do not have to stop the default behaviour of the reset button. You simply have to add the onclick attribute to the button and in the function you could call the form's reset method where ever you wish and control the behaviour as you wish. The following code illustrates that
HTML:
<input type="button" value="Limpiar" onclick="resetForm(this);"/>
JavaScript:
function resetForm(element) {
//Do what you need before reset the form
element.form.reset(); //Reset manually the form
//Do what you need after reset the form
}
try
$('your-form').bind('reset', function() {
alert('hi');
});
Here an example using the onreset event similar to how you normally use the onsubmit event of the form element to catch clicking on a submit button. The onsubmit example is added for clarification.
In your script:
function submitForm(form){
var xhr = new XMLHttpRequest(),
data = new FormData(form);
xhr.open("POST", url, true);
xhr.onload = function(event) {
switch (event.target.status){
case 200:
onSuccess(event);
break;
default:
onError(event);
}
};
xhr.send(data);
return false;
}
function resetForm(form){
var elements = form.elements;
// set some initial values to those form elements
return false;
}
In your html:
<form onsubmit="return submitForm(this);" onreset="return resetForm(this);">
<button type="submit">Save</button>
<button type="reset">Reset</button>
</form>
Reset the display contents when clicking the reset button.
$('.custom-file-input').on('change', function(){
const $label = $(this).next('.custom-file-label');
const fileName = $(this).val().split('\\').pop();
$label.data('default', $label.html());
$label.addClass('selected').html(fileName);
});
$('form').on('reset', function(){
$('.custom-file-input').each(function(){
const $label = $(this).next('.custom-file-label');
$label.html($label.data('default'));
});
});
I ended up using a promise to allow me to chain dom changes together. That way I can ensure the form is reset first, before resetting other dom stuff which needs to change based on input in the form, which includes resetting the form too. I don't necessarily expect the form reset to fail, so I don't use the reject function:
const form = document.getElementById("saveForm");
const resetBtn = form.querySelector("button[type=reset]");
resetBtn.addEventListener("click", function overrideReset(e) {
e.preventDefault();
return new Promise((resolve, reject) => resolve(form.reset())).then(() => {
//run code here.
});
});
would this help
$("input[type='reset']").on("click", function(){
alert("the form has been reset");
});
link to jsfiddle: http://jsfiddle.net/sdkTz/1/
Add a click event to the reset button, and have it look like this:
function(e) {
setTimeout(function() {
// your actual code here
},1);
}