Skip to content Skip to sidebar Skip to footer

HTML Form - Fill Input With Value If Nothing Is Entered

I'm creating a basic subscribe form for a system that requires both email address and last name (SugarCRM in case anyone is interested). I need to populate the last name input valu

Solution 1:

Check the lastname on submit of the form, if it doesn't have value, put "foo" in it:

$('#formId').submit(function() { // attach submit handler to the form.
    var $lastName = $('#lastName'); // get the last name element.
    if (!$lastName.val())   // if it doesn't have value.
        $lastName.val('foo'); // put foo as a value.
});​

You should replace formId and lastName to the actual ids of the form and last name element.


Solution 2:

Yes, this is for sure possible with jQuery. Just look at the jQuery API and then register an event to the submit button, so, that the event is executed before the submit action. There are several possibilities.

Using selectors you can search your last name input field and read and compare the entered value. If needed you can then change the value of your input field.

Just take a look at http://api.jquery.com/. Study there the events, selectors and manipulation values. Examples are pretty well self explaining.


Post a Comment for "HTML Form - Fill Input With Value If Nothing Is Entered"