tadam logo
Did you find an error in the text?
Select this with mouse and press
Ctrl + Enter
Xhtml.co.il Check Spelling
Orphus system

select()

.select( handler(eventObject) )

Returns: jQuery

Description: Bind an event handler to the "select" JavaScript event, or trigger that event on an element.

.select( handler(eventObject) )

version added: 1.0
handler(eventObject)
A function to execute each time the event is triggered.

.select( )

version added: 1.0

.select( [ eventData ], handler(eventObject) )

version added: 1.4.3
eventData
A map of data that will be passed to the event handler.
handler(eventObject)
A function to execute each time the event is triggered.

This method is a shortcut for .bind('select', handler) in the first variation, and .trigger('select') in the second.

The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.

For example, consider the HTML:

<form>
  <input id="target" type="text" value="Hello there" />
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the text input:

$('#target').select(function() {
  alert('Handler for .select() called.');
});

Now when any portion of the text is selected, the alert is displayed. Merely setting the location of the insertion point will not trigger the event. We can trigger the event manually when another element is clicked:

$('#other').click(function() {
  $('#target').select();
});

After this code executes, clicks on the Trigger the handler will also alert the message:

Handler for .select() called.

In addition, the default select action on the field will be fired, so the entire text field will be selected.

The method for retrieving the current selected text differs from one browser to another. A number of jQuery plug-ins offer cross-platform solutions.

Examples

Example 1

To trigger the select event on all input elements, try:

$("input").select();

Example 2

To do something when text in input boxes is selected:
    $(":input").select( function () { 
      $("div").text("Something was selected").show().fadeOut(1000); 
    });


The output of the code above will be:

Example 2 - Full source:

<!DOCTYPE html>
<html>
<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" language="javascript">

  $(document).ready(function(){

    $(":input").select( function () { 
      $("div").text("Something was selected").show().fadeOut(1000); 
    });
  });
  </script>
  <style>
  p { color:blue; }
  div { color:red; }
  </style>
</head>
<body>
  <p>Click and drag the mouse to select text in the inputs.</p>
  <input type="text" value="Some text" />
  <input type="text" value="to test on" />
  <div></div>
</body>
</html>
Was this information helpful?
   

Comments