copenndthagen
copenndthagen

Reputation: 50722

Conditionally disable checkbox in jQuery return

I have the following code;

var isEditable = !self.model.hasPrivilege("UPDATE_INFO") || !self.editInfo;

return "<input type='checkbox' name='flag' class='flag' />";

Now my question is while doing the return for the input, can I add condition for isEditable as part of the same return "<input type='checkbox'

Basically I want to return disabled checkbox if isEditable is false and vice-versa ?

Upvotes: 1

Views: 149

Answers (2)

Ashish Kumar
Ashish Kumar

Reputation: 3039

I think if this is jQuery, you can make it more clear like this:

var isEditable = !self.model.hasPrivilege("UPDATE_INFO") || !self.editInfo, 
    $checkBox = $("<input />", {
        type : "checkbox",
        name : "flag",
        class : "flag",
        disabled : !isEditable // condition to make the returned checkbox disabled
    });

return $checkBox;

this way, even if want to bind some events to the returned checkbox element, you can do that via adding another key to the second parameter object like:

$checkBox = $("<input />", {
    type : "checkbox",
    name : "flag",
    class : "flag",
    disabled : !isEditable, // condition to make the returned checkbox disabled,
    click : doSomething // attached some event
});

Upvotes: 0

hon2a
hon2a

Reputation: 7214

return '<input type="checkbox" ' + (isEditable ? 'disabled="disabled"' : '') + ' .../>';

Upvotes: 2

Related Questions