I have multiple textareas in my HTML form followed by an edit link for each. When I click an edit link, the corresponding textarea should be enabled. My code is as follows:
<script type="text/javascript">
$(document).ready(function() {
$(".edit").click(function(){
$(this).attr("id").removeAttr("disabled");
});
});
</script>
<textarea id="txt1" disabled="true"></textarea>
<a class="edit" id="txt1" >edit</a>
<textarea id="txt2" disabled="true"></textarea>
<a class="edit" id="txt2" >edit</a>
Why is the textarea not being enabled when the corresponding link is clicked?
id
s can only be used once in a page. you can't have 2 elements (or more) having the same id.
instead, do this:
<form id="myform">
<!-- group each in divs -->
<div>
<textarea disabled="true"></textarea>
<a class="edit">edit</a>
</div>
<div>
<textarea disabled="true"></textarea>
<a class="edit">edit</a>
</div>
</form>
<script>
$(function(){
$('#myform').on('click','.edit',function(){
$(this) //when edit is clicked
.siblings('textarea') //find it's pair textarea
.prop("disabled", false) //and enable
return false;
});
});
</script>
if you can't use divs, then you can use prev('textarea')
instead of siblings('textarea')
to get the preceding textarea.
You're re-using ID values - this is a big no-no. If you're going to give these an ID, you need to do something to differentiate the txt1
link from the txt1
textarea. In the code below, I've added a _link
suffix to the links.
<textarea id="txt1" disabled="true"></textarea>
<a class="edit" id="txt1_link">edit</a>
<textarea id="txt2" disabled="true"></textarea>
<a class="edit" id="txt2_link">edit</a>
With that small change, we can now modify the disabled property of the textarea:
$(".edit").on("click", function(e){
$( "#" + this.id.replace("_link", "") ).prop("disabled", false);
e.preventDefault();
});
The selector, unfortunately, includes a use of the replace()
method. If you remove the ambiguity in ID's between the links and the textareas, you can do away with this.
Demo: http://jsbin.com/unebur/edit#javascript,html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With