Reputation: 3
I want to always make only one input enable. To achieve that, I can disable inputs by adding disabled
attribute and remove that attribute on clicking by jQuery. Like this:
$('input').on('click', function(){
$(this).prop('disabled', false);
})
input, div{
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" disabled ><br>
<input type="text" disabled ><br>
<input type="text" disabled >
</form>
Unfortunately nothing happens on click. What's wrong and how can I fix it?
Upvotes: 0
Views: 55
Reputation: 8249
Instead of disabled
, you can use readonly
because disabled
elements don't have events (you can check this answer).
$('input').on('click', function() {
$('input').prop('readonly', true);
$(this).prop('readonly', false);
})
input,
div {
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" readonly><br>
<input type="text" readonly><br>
<input type="text" readonly>
</form>
Upvotes: 0
Reputation: 10340
Disabled elements don't execute mouse events. So you should select them indirectly. One way is adding an element in front of the disabled input to simulate clicking on that element. This is the only way for complete cross browser compatibility.
Noted that you should hide/show that element on click
:
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
and on blur
:
$(this).prop("disabled", true).next("div").show();
Full Version Of The Code:
$('form#myform > div').on('click', function(){
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
})
$('form#myform > input').on('blur', function(){
$(this).prop("disabled", true).next("div").show();
})
input, div{
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
div{
/* border: 1px solid red; */
position: absolute;
margin-top: -22px; /* I've used 22 instead of 20 because of input border */
cursor: text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" disabled >
<div></div>
<br>
<input type="text" disabled >
<div></div>
<br>
<input type="text" disabled >
<div></div>
<br>
</form>
Upvotes: 1