Blorner

Saturday, February 13, 2010

Text counter by JavaScript

This is an example for adding a counter to the inputing texts of tags <textarea> and <input>:


<html>

<head>
<title>Text Counter</title>

<script type="text/javascript">
function text_counter(textfield_id,counter_id,count){
count = parseInt(count);

document.getElementById(counter_id).innerHTML = count;

document.getElementById(textfield_id).onpropertychange = function(){
text_count_changed(textfield_id,counter_id,count);
}
}

function text_count_changed(textfield_id,counter_id,count){
if(count-parseInt(document.getElementById(textfield_id).value.length)<0){
document.getElementById(textfield_id).value = document.getElementById(textfield_id).value.substr(0,count);
}

document.getElementById(counter_id).innerHTML = count-parseInt(document.getElementById(textfield_id).value.length);
}
</script>
</head>

<body>
<p>
<script type="text/javascript">inputtext_approving_chars_count = 10;</script>
<input type="text" id="inputtext" oninput='text_count_changed("inputtext","inputtext_counter",inputtext_approving_chars_count);'> <span id="inputtext_counter"></span>
<script type="text/javascript">text_counter("inputtext","inputtext_counter",inputtext_approving_chars_count);</script>
</p>

<p>
<script type="text/javascript">textfield_approving_chars_count = 255;</script>
<textarea id="textfield" cols="50" rows="10" oninput='text_count_changed("textfield","textfield_counter",textfield_approving_chars_count);'></textarea> <span id="textfield_counter"></span>
<script type="text/javascript">text_counter("textfield","textfield_counter",textfield_approving_chars_count);</script>
</p>

</body>

</html>

No comments:

Post a Comment

Art Works Expo