Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Disable Form Fields

Tags:

jquery

forms

I have 2 fields: 1 input, 1 select box.

Is it possible to make the browser disable one of the fields when the user uses the other?

For example, if the user is entering data into the input, the select box is disabled. If the user is selecting data from the select (dropdown), the input is disabled.

Any help with this would be much appreciated.

Cheers in advance.

like image 757
user159025 Avatar asked Sep 07 '09 02:09

user159025


People also ask

How do I disable form fields?

To disable form fields, use the CSS pointer-events property set to “none”.

How do I turn off complete form?

Disabling all form elements HTML form elements have an attribute called disabled that can be set using javascript. If you are setting it in HTML you can use disabled="disabled" but if you are using javascript you can simply set the property to true or false .


2 Answers

<script type="text/javascript" src="jquery.js"></script>           <script type="text/javascript">   $(document).ready(function() {       $("#suburb").blur(function() {           if ($(this).val() != '')               $("#post_code").attr("disabled", "disabled");           else               $("#post_code").removeAttr("disabled");       });        $("#post_code").blur(function() {           if ($(this).val() != '')               $("#suburb").attr("disabled", "disabled");           else               $("#suburb").removeAttr("disabled");       });   }); </script> 

You'll also need to add a value attribute to the first option under your select element:

<option value=""></option> 
like image 108
Matt Howell Avatar answered Sep 21 '22 21:09

Matt Howell


The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true); 

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false); 
like image 30
MetaSkills Avatar answered Sep 24 '22 21:09

MetaSkills