Skip to content Skip to sidebar Skip to footer

Select/unselect Text On Click Using Jquery

I want to create the following behavior in IE9: Clicking on the textbox will select the text from the textbox. Clicking on it again will unselect the text. I tried the following f

Solution 1:

The problem with several text boxes would be that your x variable is global. You'd need a separate x variable per textbox.

You could use a map:

var x = {};

functionselectIt(obj)
{
    var key = ... <-- get name (or id) of textbox from obj somehow to use as key in map
    if (!x.hasOwnProperty(key)) x[key] = 0;
    if (x[key] % 2 == 0)
    {
        obj.select();
    }
    else
    {
        if (document.selection)
        {
            document.selection.empty();
            obj.blur();
        }
        else
        {
            window.getSelection().removeAllRanges();
        }
    }
    obj.focus();
    x[key]++;
}

Solution 2:

Here is your complete solution.

Demohttp://codebins.com/bin/4ldqp79

HTML

<div id="panel">
  <inputtype="text" value="Click Me to Select Text" />
  <inputtype="text" value="Click Me to Select Text" />
  <inputtype="text" value="Click Me to Select Text" />
  <inputtype="text" value="Click Me to Select Text" />
  <inputtype="text" value="Click Me to Select Text" />
  <inputtype="text" value="Click Me to Select Text" />
</div>

JQuery

$(function() {
    $("#panel input[type=text]").click(function() {
        $(this).select();
    });
});

CSS

input{
  display:block;
  border:1px solid #333;
  background:#efefef;
  margin-top:15px;
  padding:3px;
}

Demohttp://codebins.com/bin/4ldqp79

Solution 3:

This works for me in Chrome - there is a toggle event function in jQuery but it is not needed in this case

$('input').click(function() {
 // the select() function on the DOM element will do what you wantthis.select();
});

​ but I suggest you tell the script which types of fields you want to select

$("input[type=text], input[type=url]").click(function() {
  $(this).select(); // "this" is native JS 
});

DEMO

Solution 4:

Try this Demo

DEMO jQuery:

$(function(){
    $("input[type='Text']").on("click",function(){
     if (typeofthis.selectionStart == "number") 
         this.select();
    });
  });

Post a Comment for "Select/unselect Text On Click Using Jquery"