Tuesday, 30 October 2007

Split an input text using javascript

This tutorial explains how to split an input text using a javascript function that finds space char between two words and splits them into substring while you type.

Splitted string appears inside a layer below the input text.



Download this tutorial


Step 1: The HTML Code
We have need just an input field and a div layer:

<input name="tag" type="text" id="tag" size="30" onKeyUp="javascript:getTag();" autocomplete="off"/>
<div id="splitResponse"></div>



Step 2: The Javascript function
This is the function that split the texi in input inside the html input element named "tag":


<script language="javascript">
function getTag(){
newTagArray = new Array();
// input field
tagInput = document.getElementById('tag');
totalChar = tagInput.value.length;
// layer for the split response
destLayer = document.getElementById('splitResponse');
destLayer.innerHTML='';
// optional: format the input field in lower case
tagString = tagInput.value.toLowerCase();
// find the space position between two words
position = tagString.indexOf(' ');
i = 0;
while(position>=) {
tagStringN = tagString.substring(0, position);
newTagArray[i] = '<a href="#">'+tagStringN+'</a> ';
tagString = tagString.substring(position+1, totalChar);
position = tagString.indexOf(' ');
// Create a new <span> element to append inside the layer splitResponse
var element = document.createElement('span');
element.innerHTML = newTagArray[i];
destLayer.appendChild(element);
i=i++;
}
}
</script>


Download this tutorial

No comments:

Post a Comment