The text box's word limiter is malfunctioning when writing code on a child page of the master

Encountering an unexpected problem that I never thought would happen. I wrote a word limiter code for a text box on a single page and it was working perfectly fine. The word limiter worked and the remaining words were displayed by a label named "remaining6". However, when I copied the same code into a child page of the master page, the word limiter functionality works but the remaining words are not displayed:

<input type="text" id="TextBox5"  placeholder="latest" runat="server"  onkeyup="countChar(this)" /> 
<h5 >Characters Left <span id="remaining6">20</span></h5>
    <script type="text/javascript" >
        function countChar(val) {
            var len = val.value.length;

            if (len >= 10) {
                val.value = val.value.substring(0, 10);                                       
            } 
           else
              {                   
                $('.numbersofChart').text(10 - len);
                alert("before");
                var textEntered = document.getElementById('TextBox5').value;
                alert("after");
                var msg = document.getElementById('remaining6');
                var counter = (10 - (textEntered.length));
                msg.textContent = counter;

            }
        };
    </script>

While debugging this code using alerts, "before" is displayed but "after" is not. This indicates an error in the line:

  var textEntered = document.getElementById('TextBox5').value;

I'm unsure why the code is not executing from this point. It's worth noting that the code runs smoothly on a single page (without the master page).The issue arises when pasted into a child page of the master. I've ensured that all necessary libraries are included in the child page. How can I solve this problem?

Answer №1

Here is an illustration of a word limit scenario:

//<![CDATA[
/* js/external.js */
var doc, bod, dE, I, wordCap; // for future use
addEventListener('load', function(){
doc = document; bod = doc.body; dE = doc.documentElement;
I = function(id){
  return doc.getElementById(id);
}
wordCap = function(context, remainElement, limit){
  var s = context.value.split(/[ ]+/), max = limit || 20;
  var n = max-s.length;
  if(n < 1)n = 0;
  remainElement.innerHTML = n;
  
  if(n === 0){
    context.value = s.splice(0, max).join(' ');
  }
}

var remainingCount = I('remain');
I('textBox').onkeyup = function(){
  wordCap(this, remainingCount);
}

}); // end load
//]]>
/* css/external.css */
*{
  box-sizing:border-box; padding:0; margin:0;
}
html,body{
  width:100%; height:100%;
}
body{
  background:#ccc;
}
#content{
  padding:7px 5px;
}
#textBox{
  width:100%; height:38px; background:#fff; color:#000; font:22px Tahoma, Geneva, sans-serif; padding:5px;
}
h5{
  text-align:center;
}
h5>span{
  color:#a00;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
    <title>Word Limit Tracker</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script type='text/javascript' src='js/external.js'></script>
  </head>
<body>
  <div id='content'>
    <input id='textBox' type='text' />
    <h5>Words Left <span id='remain'>20</span></h5>
  </div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Could anyone clarify the concept of how a function is able to be equivalent to zero?

function checkForSpecialCharacters(text) { var specialChars = [";", "!", ".", "?", ",", "-"]; for(var i = 0; i < specialChars.length; i++) { if(text.indexOf(specialChars[i]) !== -1) { return true; } } ...

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Instructions on deactivating the background when the sidebar is displayed and closing the sidebar by clicking anywhere other than the sidebar

I'm in the process of creating a sidebar for my website. When the sidebar is displayed (by clicking showRight), I want to disable the background content so that the user can't interact with anything outside of the menu. If the user clicks on th ...

challenges with managing memory during express file uploads

I'm experiencing memory problems with file uploads while hosting my site on NodeJitsu. When I try to upload files, my app crashes with this error message: { [Error: spawn ENOMEM] code: 'ENOMEM', errno: 'ENOMEM', syscall: 'spa ...

Determine whether a request is for CSS or JavaScript when using NodeJS and Express

My routing configuration includes the following setup: app.get('*', function (req, res, next) { req.xhr ? next() : res.render('layout/layout'); }); The idea behind this is to return the base layout if the request is not an XMLHttp ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Add Text to HTML and Delete Added Content Upon Button Click

I have successfully implemented code that appends new content to the div "users". However, I am facing an issue with removing the appended content when a user clicks a button. Currently, the code only removes the "remove" button upon clicking. But I need ...

HTML5 Boilerplate and optimizing the critical rendering path by deferring scripts and styles

Previously, I constructed my website layouts using the HTML5 Boilerplate method: incorporating styles and Modernizr in the head section, jQuery (either from Google CDN or as a hosted file) along with scripts just before the closing body tag. This is an exa ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

How to display text on a new line using HTML and CSS?

How can I properly display formatted text in HTML with a text string from my database? The text should be contained within a <div class="col-xs-12"> and nested inside the div, there should be a <pre> tag. When the text size exceeds the width o ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Determine the total number of nested objects within a JSON structure using Javascript

Consider the JSON structure below: { "id": "foo", "list": [ { "id": "A", "list": [ { "id": "B", "list": [ { "id": "C", "list": [ { ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Utilizing Bootstrap to allow for seamless text wrapping around a text input field

I am trying to implement a "fill-in-the-blank" feature using Bootstrap, where users need to enter a missing word to complete a sentence. Is there a way to align the text input horizontally and have the rest of the sentence wrap around it? This is my curr ...

What is the method for retrieving the status of an xmlHttpRequest?

I'm curious about how to verify the status of an xmlHttp request once it has been sent. Can someone explain the process to me? Thank you. function sendRequest(){ //retrieve access token var accessToken = 'xxx'; //get user_id ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Incorporating JavaScript to dynamically load an HTML page into an iframe

I am attempting to have each option load a unique page within a frame <!DOCTYPE html> <html> <head> <script> function selectCountry() { var mylist=document.getElementById("country"); document.getElementById("frame").src=mylist.opti ...

New to React and looking for guidance on implementing .forEach or .includes in my code

My task involves going through an array and checking if a string that the user inputs into the form exists in it. This can be achieved using forEach or .includes method. I am basically trying to filter out the array based on the input. If someone could de ...