Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove disabled attribute of a textarea using jQuery?

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?

like image 306
Micku Avatar asked May 10 '12 04:05

Micku


2 Answers

ids 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.

like image 150
Joseph Avatar answered Oct 18 '22 11:10

Joseph


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

like image 36
Sampson Avatar answered Oct 18 '22 12:10

Sampson