Pregunta

I have a form as follows:

<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>

And javascript code:

function toggleInput(){
    if ($("#input").disabled){
        $("#input").disabled = false;
    }
    else {
        $("#input").disabled = true;
    };
}

What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.

Thanks in advance!

EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:

I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.

¿Fue útil?

Solución 2

To do it with jQuery try this:

$("#input").prop("disabled", function(i, v) { return !v; });

Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.

I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:

$("#lock").on("click", function() {
    $("#input").prop("disabled", function(i, v) { return !v; });
});

(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)

Demo: http://jsfiddle.net/a7f8v/

Otros consejos

Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element

 $("#input").prop('disabled',!$("#input").prop('disabled'))

DEMO

I am not sure why you are using onMouseDown. Use click instead

$("#lock").on("click", function() {
    $("#input").prop('disabled',!$("#input").prop('disabled'))
});

DEMO with click

You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:

<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>

JavaScript:

$(document).ready(function() {
    $("#lock").click(function() {
        var input = $("#input");
        input.prop('disabled',!input.is(':disabled'))
    });
});

Example

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top