Skip to content

Instantly share code, notes, and snippets.

@mateuszkocz
Created December 8, 2013 20:33
Show Gist options
  • Save mateuszkocz/7863446 to your computer and use it in GitHub Desktop.
Save mateuszkocz/7863446 to your computer and use it in GitHub Desktop.
Text select in an input or textarea. Demo: http://jsbin.com/umEjuKu/1/edit
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form id="form">
<label>name:
<input type="text" id="txtname" value="Example name" tabindex="1" autocomplete="off"></label>
</form>
<p>Selected Text is: <strong id="output"></strong></p>
</body>
</html>
var txtname = document.getElementById('txtname');
var output = document.getElementById('output');
function getSelectedText(txt) {
return txt.value.substring(txt.selectionStart, txt.selectionEnd);
}
txtname.onselect = function () {
output.innerHTML = getSelectedText(txtname);
};
txtname.onblur = function () {
output.innerHTML = '';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment