当前位置: 动力学知识库 > 问答 > 编程问答 >

Run character count javascript function in single page only

问题描述:

I have a page which has form to edit information. I wrote a simple javascript code to count character as soon as this page is loaded. So i put <body onload='charCount()'>. It works just fine but the problem is when other pages are loaded, i got javascript error: can't get value from element id=title. My entire website using the same header and footer and the body tag is in the header.

Is there anyway to run this javascript on that particular page only? I tried to put <form onload='charCount()'> also but i did not work.

Here is my html page:

<html>

<body onload='charCount()'>

....//end header section

<form>

<input id='title' type='text' value='abcd'/>

<div id='showcharcount'></div>

</form> //end content section

<script>

function charCount(){

var x = document.getElementById("title").value;

document.getElementById("showcharacount").innerHTML = charCountFunc(x) + "/35 characters allowed";

}

function charCountFunc(x) {

var n = x.length;

return n;

}

</script>

</body>

</html> //end footer section

网友答案:

Well, if you want to run the script code on one page, and not on other pages, you can ensure that the script is attached to the said page only. Not on other page because that would be a part of garbage, code which is not used.

You can use window.onload = functionName; command which calls the function functionName() when the page got loaded.

Just add the next script at the webpage of which you want to use the function.

<script>
    function charCount(){
        ...
    }
    function charCountFunc(x) {
        ...
    }
    window.onload = charCount;
</script>

It can be done on the server side, by adding the above snippet in the template showing the form.

网友答案:

You can avoid the error by checking existence of the element first.

function charCount(){
    var elem = document.getElementById("title");
    if (elem != null) {
        var x = elem.value;
        document.getElementById("showcharacount").innerHTML = charCountFunc(x) + "/35   characters allowed";
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: