Quantcast
Viewing latest article 6
Browse Latest Browse All 10

Focus and Select

Image may be NSFW.
Clik here to view.

Focus and select issue in Google Chrome and Firefox Browsers and how to rectify it.

Suppose we’re having a requirement like once you focus a text box then the text in that particular text box should get selected.

To do that first we’ll write focus event and then select function. Please create html file with the below code. In this I’m using JQuery library to handle the events so, download theJQuery library and place the same in current directory where html file resides and change the value of src accordingly.src attribute is in 4th line of our code.

<html>

<head>

<title>Focus & Select</title>

<scripttype=”text/javascript”src=”jquery-1.10.2.js”></script>

<scripttype=”text/javascript”>

$(function () {

$(“#focusSelectId”).focus(function () {

$(this).select();

});

//$(“#focusSelectId”).mouseup(function (e) {

//    e.preventDefault();

//});

});

</script>

</head>

<body>

<inputtype=”text”value=”Focus and select”id=”focusSelectId”/>

</body>

</html>

See the above code I have created an input element of type textbox with id “focusSelectId” and with that id we are handling focus and mousup eventsusing JQuery Library.

Once a file is created execute the same in Internet Explorer, Google Chrome and Firefox.

First execute it in IE and select the textbox, then see the text in that textbox is selected but the same will not work in Google Chrome and Firefox why because mouseup event in Google Chrome and Firefox is written after the focus event, whereas in IE it is written in before focus event.

See Chrome and Firefox once you select textbox it’s selecting the text and it’s getting cleared because at focus event text is getting selected and after mouseup event text is getting unselected.

How to fix this issue?

To do this we need to prevent mouseup event. See the above code which is in green color and it is commented used to prevent the mouseup event. For every event there will be default event, to prevent that default event we’ll use e.preventDefault() function.

So uncomment it in your html code. Then execute the same in IE, Google Chrome, Firefox so focus and select will work perfectly like Fig1.

Image may be NSFW.
Clik here to view.
Fig1
Fig 1

By: Jayasankar J


Viewing latest article 6
Browse Latest Browse All 10

Trending Articles