Passa al contingut principal

Awesome jQuery snippets to work with forms

Disable “enter” key in your forms


If you want to prevent visitors to accidentally submit your form by hitting the “enter” key, you can use this snippet to disable the use of the “enter” key in your forms.



$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});

Source: http://www.catswhocode.com/blog/10-awesome-jquery-snippets


Clear form data


Need to clear all form data? Here’s a handy function to do it.



function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};

Source: http://www.jquery4u.com/forms/jquery-function-clear-form-data/#.UI02J2knDF8


Find is a checkbox is checked


Find out if a single checkbox is checked or not. The function will returns true or false:



$('#checkBox').attr('checked');

Source: http://jquery-howto.blogspot.be/2008/12/how-to-check-if-checkbox-is-checked.html


Enable/Disable form elements


Want to make your forms more user-friendly? Then you can enable or disable form elements such as the submit button. For example, you can have it disabled by default and enable it only if the form has been properly filled by the visitor.



$("#submit-button").attr("disabled", true);

And to re-enable a previously disabled input:



$("#submit-button").removeAttr("disabled");

Source: http://css-tricks.com/snippets/jquery/disable-re-enable-inputs/


Enable submit button if text entered


Here’s a variant of the above snippet, this time allowing you to automatically enable the submit button if some text is entered in a #username input field.



$('#username').keyup(function() {
$('#submit').attr('disabled', !$('#username').val());
});

Source: http://cakebaker.42dh.com/2009/01/13/enabling-submit-button-if-text-entered/


Submit form programmatically


Super simple but definitely useful: Here’s how to submit a form programmatically using jQuery.



$("#myform").submit();

Source: http://www.jquery4u.com/snippets/jquery-simulate-form-submit/


Prevent multiple submit of your form


Multiple submissions of the same form is definitely one of the most common problem seen when working with web forms. Here’s a super useful piece of code to prevent multiple submissions of the same form.



$(document).ready(function() {
$('form').submit(function() {
if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
jQuery.data(this, "disabledOnSubmit", { submited: true });
$('input[type=submit], input[type=button]', this).each(function() {
$(this).attr("disabled", "disabled");
});
return true;
}
else
{
return false;
}
});
});

Source: http://damienalexandre.fr/post/2009/08/02/jQuery-eviter-la-soumission-multiple-d-un-formulaire


Highlight related label when input in focus


Another way to make your form easier to fill for your visitors: Highlight related label when input in focus. Here’s some jQuery goodness to help.



$("form :input").focus(function() {
$("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
$("label").removeClass("labelfocus");
});

Source: http://css-tricks.com/snippets/jquery/highlight-related-label-when-input-in-focus/


Dynamically add form elements


If you need to dynamically add form elements, the snippet below is a simple way to do it.



//change event on password1 field to prompt new input
$('#password1').change(function() {
//dynamically create new input and insert after password1
$("#password1").append("<input type='text' name='password2' id='password2' />");
});

Source: http://www.jquery4u.com/forms/jquery-dynamically-add-form-elements/


Auto-populating select boxes using Ajax & JSON


When building an interactive form, it is very useful to be able to get some data with ajax and use it to populate a select element.

The following snippet shows how to get data from a php file named select.php (line 3) and populate a select element with it.



$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#ctlPerson").html(options);
})
})
})

Source: http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/






via CatsWhoCode.com http://www.catswhocode.com/blog/awesome-jquery-snippets-to-work-with-forms

Comentaris

Entrades populars d'aquest blog

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

El meu editor de codi preferit el 2024, que això ja se sap que va canviant 😄

Visual Code Visual Code és un editor de codi font lleuger, però potent que s’executa al teu escriptori i està disponible per a Windows, macOS i Linux. Compta amb suport integrat per a JavaScript, TypeScript i Node.js i té un ric ecosistema d’extensions per a altres llenguatges i entorns d’execució (com C++, C#, Java, Python, PHP, Go, .NET).  És una eina ideal per a desenvolupar i depurar aplicacions web i en el núvol. Per què Visual Code? Visual Code té molts avantatges com a editor de codi font, com per exemple: És gratuït, ràpid i fàcil d’instal·lar i actualitzar. Té un ampli ecosistema d’extensions que et permeten afegir funcionalitats i personalitzar la teva experiència de desenvolupament. Té un suport integrat per a molts llenguatges i entorns d’execució, i et permet depurar i executar el teu codi des del mateix editor. Té una interfície senzilla i elegant, amb diferents temes i modes de visualització. Té un sistema de sincronització de configuracions que et permet guardar les...

Las Mejores Aplicaciones Gratis para iPad de 2012

Las Mejores Aplicaciones Gratis para iPad de 2012 : ¿No tienes ni un duro? No te preocupes, pues hoy os traemos una extensa selección de las mejores apps gratuitas que puedes conseguir en la App Store para que llenes tu iPad de calidad, sin gastar nada de nada.   ¿Estás buscando juegos o apps gratis para tu iPad? En la App Store hay más de 500,000 apps y juegos, y una gran cantidad de ellos está disponible de forma totalmente gratuita. Aquí vamos con la selección de las mejores Apps gratis para iPad (todos los modelos), organizada por categoría. ¿Estás preparado? Las Mejores Apps Gratis de Redes Sociales para iPad Nombre Facebook Gratis Categoría Redes sociales Facebook es la red social más famosa del mundo , con casi mil millones de usuarios. Su app para iPad ha tardado, pero aquí está. Nombre Twitter Gratis Categoría Redes sociales Twitter es la red de microblogging por excelencia. La forma más rápida y directa de informar y mantenerse informado de las cosa...