andy-h
10/30/2015 - 2:44 PM

Go to a specified line & character within a text box

Go to a specified line & character within a text box

<!DOCTYPE html>

<html lang="en">
<head>
	
	<meta charset="utf-8">
	
	<title>Go To Line/Character</title>
	
</head>
<body>
	
	<form action="javascript:go();">
		<textarea id="txt" rows="25" cols="150"></textarea><br>
		<br>
		<label>Line <input type="number" id="line" step="1" min="1" value="1"></label><br>
		<label>Char <input type="number" id="char" step="1" min="1" value="1"></label><br>
		<input type="submit" id="go" value="Go">
	</form>
	
	<script type="text/javascript">
		function go(){
			var txt = document.getElementById("txt"),
				line = document.getElementById("line").value,
				char = document.getElementById("char").value,
				rxp, before, loc;
			
			rxp = new RegExp("^(.*\n){"+(line-1)+"}");
			before = rxp.exec(txt.value);
			if(!before){	//the text has fewer than `line` lines
				//put the cursor at the end of the text
				before = txt.value;
				char = 0;
			}
			else{
				before = before[0];
				char--;
			}
			loc = before.length + 1*char;
			txt.setSelectionRange(loc, loc+1);
			txt.focus();
		}
	</script>
	
</body>
</html>