Number of downloads: 1174
Number of downloads: 796Hi,
This tutorial shows how to channge the text under any element in HTML on the fly using Javascript.
Consider a very basic example, though not much usable practically but it will build our base for more example that come our way.
Say you have a table and within it you want to change the text displayed whenever someone clicks a button. The html for it will be:
<html>
<script>
function changeText()
{
document.all['text'].innerText = "ample Text";
}
</script>
<body>
<input type=button name="mybutton" value="Change the text" onclick="changeText()"/>
<table>
<tr>
<td id="text">
Sample Text
</td>
</tr>
</table>
</body>
</html>
Lets understand the above code.
1) In the body we have a button whose onclick calls a javascript function
2) A table is there having a row and that row as a column whom we have given a id as "text". This column has the text as "Sample Text"
3) The function changeText gets the column using the document.all['text'] and then changes the innerText attribute of the column to "ample Text"
4) That's it
It gives the effect to user that some thing has been overwritten.
That's not possible with document.write().
Now lets come to some practical thing. Suppose you have a page where in you allow the user to choose for a new request or update an exisiting record. And if it is a new request, you want the submit button to be Record New and if it is an update request then it should read Update.
Lets have the code for doing this:
<html>
<script>
function changeText()
{
if(radiobtn[0].checked)
{
mybutton.innerText = "Record New";
}
else
{
mybutton.innerText = "Update";
}
}
</script>
<body>
Record New
<input type=radio name="radiobtn"
checked
onclick="changeText();"
/>
Update
<input type=radio name="radiobtn"
onclick="changeText();"
/>
<br>
<button type="button" name="mybutton">
Record New
</button>
</body>
</html>
Lets understand the code:
1) In html we have declared two radio buttons with same name so that only one can be selected at a time and onclick of both calls the same javascript function.
2) Then we have a button not with <input typ="button"/> but as <button....></button. The advantage of latter is that it allows css to be used but the former can't use css for the button. With in the button tags we have written "Record New" because our record new radio button is checked by default.
3) The javascript function gets the button by using the name. Had it been inside a form named form1. Then the code in changeText would have been
form1.mybutton.innerText= "......"
4) By changing the innerText property depending upon the radio button selected we achieve the desired effect.
That's all, now you can play around with any HTML element which is declared as <xxx>"some text"</xxx> and change its innerText attribute to make your pages more live.
Just for convenience, I am attaching both the example as .htm files. You can download them and see the effect.





MultiQuote




|