Ever wonder how to disable another input element through the use of another control? Here is a simple tutorial on how to toggle the disabled attribute of an input element.
For the first demo, we will toggle an input’s disabled status through the use of another control. For this example, we will give our target input an id of target, while our control, in this case a link, we will give it an id of control:
Target text field: <input type="text" id="target" /><br />
<a href="#" id="control" />Disable target</a>
Now to toggle the target’s disabled status, it is actually quite simple in jQuery. Using the .attr() attribute we can disable the target. Then using the .removeAttr(), we can remove the disabled status. Here is how the javascript code would look like:
$("#control").toggle(
function ()
{
$('#target').attr("disabled", true);
},
function ()
{
$('#target').removeAttr("disabled");
});
Here is a demo on how to toggle the disabled status of an input:
Target text field:
<input id="target" type="text"> Disable target
Although the first method is handy, there are times when we really don’t need a control input. What if we want to enable an input textbox just by clicking on it? Unfortunately, when an input element is disabled, it would no longer register events such as focus or click. The good news is that there is an alternative. Instead of using the disabled attribute, we use the readonly attribute instead. Here is a sample javascript code on making a readonly input enabled using its click event:
$('#readonly').click(
function()
{
if ($('#readonly').attr("readonly") == true)
{
$('#readonly').val('');
$('#readonly').removeAttr("readonly");
}
});
Here is the demo of how to change the readonly attribute
This text field will no longer be read-only upon clicking:
<input id="readonly" value="click me to enable" type="text">
If you want to download the source code for this tutorial,
just click on the link below:
'JQUERY' 카테고리의 다른 글
jquery, jstree 사용. 자식노드 선택시 부모노드 선택하는 스크립트 (0) | 2014.08.08 |
---|---|
[jQuery] ajaxSubmit - 심플한 ajax 통신 (1) | 2014.06.24 |
ACE-T's JS Part 03. Jquery 기초를 배워봅시다! (0) | 2014.06.24 |
[jQuery] 따라다니는 배너, 스크롤 배너 (1) | 2014.06.11 |
[jQuery] 별점 플러그인 (0) | 2014.06.11 |
[Jquery]따라다니는 설명창 (0) | 2014.06.11 |
[Jquery] 검색어 하이라이트, 색상 변경 (0) | 2014.06.11 |
[jQuery selectBox]자바스크립트 onchange 를 jquery에서는? (0) | 2014.06.11 |