Disabling and Enabling Form Elements - J Query

Problem
Your order form has fields for both shipping and billing contact information. You’ve decided to be nice and supply the user with a checkbox that indicates the user’s shipping information and billing information are the same. When checked, the billing text fields should be disabled:

Solution 1

If all you want to do is disable the billing fields, it’s as simple as using the jQuery .attr() and .removeAttr() methods when the change event is triggered:

Solution 2

While selecting a checkbox and disabling the form fields might be enough to get the point across to the user, you could go the extra mile and prepopulate the billing text fields with data from shipping information.
The first part of this solution is the same in structure as the solution shown previously. However, in addition to disabling the billing fields, we are also pre populating them with data from the shipping fields. The following code assumes the shipping and billing <fieldset> elements contain the same number of text inputs and that they are in the same order:

The second part of this solution updates the billing fields automatically when the userenters information into the shipping fields, but only if the billing fields are otherwise disabled:

Discussion

In the preceding solution I’m using the input:text selector to avoid disabling the checkbox itself.
Using .trigger('change') immediately executes the .change() event. This will check the state of the checkbox initially, in case it is checked by default. Also, this protects against Firefox and other browsers that hold on to radio button and checkbox states when the page is refreshed.
What will happen when JavaScript is disabled? You should hide the checkbox by default in CSS. Then use JavaScript to add a class name to a parent element that would override the previous CSS rule. In the following example code I’ve added an extra<div>surrounding the checkbox and label so they can be easily hidden:

As an alternative to hiding the checkbox in CSS and showing it using JavaScript, you could add the checkbox to the DOM using JavaScript. I prefer to keep my HTML, CSS,and JavaScript separate, but sometimes this is the better solution:


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics