Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't this simple javascript/jquery code alert selected text?
    primarykey
    data
    text
    <p>I can't explain the behaviour of the code below. Here's my entire script</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" language="javascript"&gt; var tmpText = ''; $(document).ready(function(){ tmpText = ''; $('#btn_bold').click(function(){alert(tmpText);}); $('textarea').bind('mouseup', function(){ tmpText = ''; if(window.getSelection){ tmpText = window.getSelection(); }else if(document.getSelection){ tmpText = document.getSelection(); }else if(document.selection){ tmpText = document.selection.createRange().text; } //tmpText = 'hello world'; alert(tmpText); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button type="button" id="btn_bold"&gt;click&lt;/button&gt; &lt;textarea&gt;This is some text&lt;/textarea&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Try the following operations:</p> <p>1) Use your mouse to high light text in the text area. You will notice that javascript alerts you the selected text.</p> <p>2) Press the click button. You will notice javascript will alert you an empty string.</p> <p>No uncomment <code>tmpText = 'hello world';</code> and repeat the above steps. This time, you'll notice both steps 1) and 2) alerts you "hello world".</p> <p>How come in the first experiment, step 2) does not alert you the same text as step 1)?</p> <p><strong>I am testing in google chrome</strong></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload