jQuery Snippet: Enable Submit if Input Field has Value

A cool thing that jQuery allows you to do is enable and disable certain elements based on particular conditions. The following snippet shows you how to enable a submit button that has been disabled if text has been entered into an input field. If the input field has a value, then the form can be submitted, but if it doesn’t, then it can’t. The concept is pretty straightforward and makes a lot of sense, because often forms are submitted without being filled out properly or entirely.

To achieve this effect, we can use the jQuery .attr() method to change the disabled/enabled attribute based on the condition of whether or not the input field contains a value. For the purposes of the example below, let’s say that the input field in question has an ID of “#text”, and the submit button has an ID of “#submit”:

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

That’s it! Just two lines of jQuery will take care of enabling a submit button based on any input field of your choosing having value.

Continue Reading Below

Comments are closed.

Sorry, but comments for this entry are now closed.