Avrohom Yisroel Avrohom Yisroel - 1 year ago 57
Javascript Question

jQuery disabling input not working

I have some input elements on a page, and am trying to enable them or disable them according to the setting of a pair of radio buttons. I'm using the following Javascript function (console logging added for me to see what's going on)...

function EnableIndividualOrCompanyControls(individual) {
console.log("EnableIndividualOrCompanyControls(" + individual + ")");
console.log("Title value is " + $("#Title").val());
console.log("Title was " + $("#Title").prop("disabled"));
$("#Title").prop("disabled", !individual);
console.log("Title is now " + $("#Title").prop("disabled"));
console.log(" ");
$("#Surname").prop("disabled", !individual);
$("#CompanyName").prop("disabled", individual);

When the radio button value is changed, the method is getting called, and the parameter has the correct value, however the Title, Surname and CompanyName inputs are never disabled.

As sample from the console looks like this...

Title value is Sir
Title was false
Title is now false

So, the function is being called, the parameter has the correct value, I am getting the Title input element correctly (as you can see from the fact that it correctly reports that its value is "Sir"), but the elements are not being disabled.

The odd thing is that I use exactly the same code elsewhere on the page, and it works fine. This function works...

function EnableOnlineControls(enable) {
$("#UserName").prop("disabled", !enable);
$("#Password").prop("disabled", !enable);
$("#PasswordAgain").prop("disabled", !enable);

Anyone any idea why the first one doesn't work? In case it helps, here is the HTML for those form elements (surrounding divs removed for clarity)...

<input class="form-control" id="Title" name="Title" value="" />
<input class="form-control" id="Surname" name="Surname" value="" />
<input class="form-control" id="CompanyName" name="CompanyName" value="" />

I tried replacing the double quotes with single ones, but that didn't make any difference.

Answer Source

The answer to JQuery readOnly strange behavior explains your problem.

individual comes from a checkbox; it is a string. You have to cast it properly to a boolean:

$("#Surname").prop("disabled", (individual == "false" ? false : true));