In this blog, I’m explaining how to enable or disable a form element using jquery.
In this blog, I will create a simple webform and have two fieldsets having two textbox in each fieldset and a check box in the second one – if we check on checkbox the second fieldsets textboxes will be disabled and the value of first fieldsets textboxes will be copied to second fieldsets textboxes and if we uncheck it, then the value of second fieldsets will be removed.
Step 1:
First create an empty asp.net application and add a webform to it and create a user interface like this:
<formid="form1"runat="server">
<div>
<fieldsetid="shippingInfo"style="width: 100px;">
<legend>Shipping Address</legend>
<labelfor="shipName">Name</label>
<inputname="shipName"id="shipName"type="text"/>
<labelfor="shipAddress">Address</label>
<inputname="shipAddress"id="shipAddress"type="text"/>
</fieldset>
<fieldsetid="billingInfo"style="width: 100px;">
<legend>Billing Address</legend>
<labelfor="sameAsShipping">Same as Shipping</label>
<inputname="sameAsShipping"id="sameAsShipping"type="checkbox"
value="sameAsShipping"/>
<labelfor="billName">Name</label>
<inputname="billName"id="billName"type="text"/>
<labelfor="billAddress">Address</label>
<inputname="billAddress"id="billAddress"type="text"/>
</fieldset>
</div>
</form>
Step 2:
Add the jquery-1.11.0.min.js file to your project and write the below code in the head section of the webform:
<scriptsrc="jquery-1.11.0.min.js"></script>
<scripttype="text/javascript">
$(document).ready(function () {
$('#sameAsShipping').change(function () {
if (this.checked) {
$('#billingInfo input:text').attr('disabled', 'disabled');// disabled the textboxes
var shipName = $('#shipName').val();
$('#billName').val(shipName); // Copy the value from one textbox to another
var shipAddress = $('#shipAddress').val();
$('#billAddress').val(shipAddress);
}
else {
$('#billingInfo input:text').removeAttr('disabled');// Enabled the textboxes
$('#billName').val("");
$('#billAddress').val("");
}
}).trigger('change');
});
</script>
Output
Now when you run the application:
Write the appropriate values in the textboxes and check on “Same as Shipping” checkbox – both the textbox of Billing Address will be disabled and values from the Shipping Address textboxes will be copied to the Billing Address textboxes and if you uncheck the checkbox:-
If you uncheck the checkbox – values from the textboxes will be removed and become enable to write.
Leave Comment