0

We have a simple textarea and a button.

<input type="button" id ="foo" disabled>
<textarea rows="12" name="message" id="message" cols="50"></textarea>

I need to:

  1. remove attribute disabled from button when some text in textarea selected
  2. set attribute disabled when selection canceled

First task was achieved with this code:$('textarea').select(function() { $('#foo').attr('disabled','');});

But with the second task i havn't any ideas.

Vit Shudra
  • 13
  • 1

3 Answers3

1

Try this

<script>
   $(document).ready(function () {
      $("#controlId").attr('disabled','disabled');  //disable the control

      $("#controlId").removeAttr('disabled');//remove disabled
   });
</script>

Don't do $("#Div").attr('disabled','true');, the main problem here is that with 1.6 (or sth around that) the comparison with == true is broken, if the attributes value is disabled (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)). You should rather go for is().

You can check jQuery FAQ.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
0

Try to use below code
$(document).ready(function () { $('textarea').select(function() {$('#foo').attr('disabled',false)}); $('textarea').mousedown(function() { $('#foo').attr('disabled',true);}); });
Could you try using focus event? Seems this event will be trigger once focusing on your DOM element. answer was NO. you can use mouse down.

Louis Weng
  • 61
  • 4
  • Button should be enabled only when some text in textarea selected. Focus event and onMouseUp aren't a right choice. – Vit Shudra Feb 01 '12 at 09:14
  • I use mousedown event.Otherwise, we can also use focus event like below answer:http://stackoverflow.com/questions/275761/how-to-get-selected-text-from-textbox-control-with-javascript – Louis Weng Feb 01 '12 at 09:38
  • With some dances with tambourine it works the right way. I thought there was real event in jQuery. Or at least select possibility to use two functions inside, like $('textarea').select(fn1{ text selected },fn2{ text unselected }); – Vit Shudra Feb 02 '12 at 07:34
0

You can get selected text using this function,

 function getSelectedText() {
        var text = "";
        if (window.getSelection) {
            text = "" + window.getSelection();
        } else if (document.selection && document.selection.createRange &&
                document.selection.type == "Text") {
            text = document.selection.createRange().text;
        }
        return text;
    }

And add new function like this in mouse up event,

function  Disable() { 
   if(getSelectedText()=='')
   {
      $('#foo').removeAttr('disabled');
   }
}

$('textarea').mouseup(Disable);
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92