Indentation in Textarea using jQuery

2014-09-21 • Snippets • Views: 1542

Indentation in Textarea using jQuery

[php]

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<script language="javascript">
$(document).ready(function(e) {

// Using the <TAB>
$(‘textarea.tab’).keydown(function(e) {
if(e.keyCode == 9) {
var start = $(this).get(0).selectionStart;
$(this).val($(this).val().substring(0, start) + "\t" + $(this).val().substring($(this).get(0).selectionEnd));
$(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1;
return false;
}
});

// Using Spaces
$(‘textarea.space’).keydown(function(e) {
if(e.keyCode == 9) {
var start = $(this).get(0).selectionStart;
$(this).val($(this).val().substring(0, start) + " " + $(this).val().substring($(this).get(0).selectionEnd));
$(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 4;
return false;
}
});
});
</script>

<h5>Using the &lt;TAB&gt;</h5>

<textarea cols="40" rows="10" class="tab"></textarea>

<h5>Using Spaces</h5>
<textarea cols="40" rows="10" class="space"></textarea>
</body>
</html>

[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Shares