Is there a way to use JavaScript to extract and display text from a textarea?

As someone who is new to JavaScript, I am currently exploring the fundamentals of this programming language. To practice, I have attempted to create a simple text editor for a webpage. Specifically, I am working on a feature that can identify whether the word "bob" has been entered into a textarea using JavaScript.

<script>

function findBob() {
    var inputText = document.getElementById("box").innerHTML;
    if(inputText === "bob") {
        document.getElementById("box").innerHTML = "true";
    } 
    if (inputText !== "bob") {
        document.getElementById("box").innerHTML = "false";
    }
}
</script>

<textarea rows=10; col= 5; id="box">
bob</textarea>

<button onClick="findBob();">FIND BOB</button>

When I click the "FIND BOB" button, it correctly changes the text to "true" if the word "bob" is present in the textarea. However, if I add random characters to the textarea and then click "FIND BOB" again, nothing happens. The function only seems to work when the textarea contains exactly the word "bob". Even after reloading the page or editing the textarea content, the function still does not execute properly.

I suspect that there may be an error in my JavaScript syntax, but I cannot pinpoint it. What could be the issue?

-EDIT- I decided to use === for comparison due to a recommendation from another discussion on StackOverflow, which you can find here.

Answer №1

The content inside a textarea is initially set to its default value.

Modifying the default value using JavaScript will only take effect if either of the following conditions are met:

  • The value has not been changed from the default value or
  • The form is reset

Once you start typing in the textarea, neither of these conditions apply anymore.

To change the current value of the textarea, use the value property instead of modifying the innerHTML.

Answer №2

@Quentin provided an answer to your fundamental question, however, you have the opportunity to enhance your code by implementing the following changes:

function searchForBob() {
  // It's more efficient to store a reference to the textarea DOM element rather than repeatedly looking it up
  const textarea = document.getElementById('box');

  // Instead of checking multiple times for a truthy condition in if statements, utilize the else component
  // Access the content of the textarea using `value` and apply `toLowerCase` to ensure case-insensitivity
  // Utilize `indexOf` to determine if 'bob' is present within the textarea contents
  if (textarea.value.toLowerCase().indexOf('bob') > -1) {
    // Update the textarea with the searched result
    // Rather than using true/false as strings, assign them directly
    textarea.innerHTML = true;
  } else {
    textarea.innerHTML = false;
  }
}

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

Tips for JavaScript validation before submitting a form in Zend framework

I created this JavaScript code for form validation, but it is also submitting data to the database even when the validation fails. I need help in modifying the code so that it only submits the data if the conditions are met. Below is the HTML code: <f ...

Ways to conceal and reveal an item within a three.js environment

In my scene, I have an object made up of spheres and a hide/show button. The process in my program goes like this: when I choose one of the spheres using raycasting and then press the hide button, that particular sphere becomes hidden. Clicking on the sh ...

The result of adding up all Object Keys is a String, rather than the anticipated Number

Can anyone assist me with a coding issue I'm experiencing? My goal is to sum up all the values of an object and store them in a single variable for the total, but it appears that I am concatenating them instead. binance.depth("BNBBTC", (error, depth, ...

How do I delete an element from an array in a MongoDB database using Node.js?

When running this query in ROBO 3T, the code executes correctly. However, when attempting to run it in nodejs, the code is not functioning as expected. //schema model const mongoose = require('mongoose'); const imageSchema = mongoose.Schema({ ...

What is the best way to input two distinct variables into the Firebase database?

I have encountered an issue while trying to upload two variables into my Firebase database. Only the first variable, newRoute, is being successfully uploaded while new User isn't getting uploaded. The setup of the Fire configuration for the entire web ...

Looking to retrieve a JavaScript code block from an AJAX response using jQuery?

How can I extract a Javascript code block from an ajax response using jQuery, while disregarding other tags (in this case, the div tag) and prevent the execution or evaluation of the Javascript code? Example in get_js.html: <script> $(function ...

Writing a JavaScript equation using three.js to orbit an object in a circular path around a central y-axis in a 3D space

Currently, I am playing around with threeJS and have managed to position the camera to look at the origin point of a scene (0,0,0). My goal is to rotate the camera in a circular path around the y axis at a specific distance (radius) while keeping its focus ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

"npm is the go-to tool for managing client-side JavaScript code

As I delved into a document outlining the npm Developer Guide, a question sprang to mind. Is it within the realm of possibility to construct a web client application using javascript/css/html with npm at the helm? And if so, might there be examples avail ...

HighCharts velocity gauge inquiry

I recently integrated a highcharts speedometer with PHP and MYSQL on my website. Everything seemed to be working smoothly until I added the JavaScript code for the speedometer, causing it not to display. There are no error messages, just a blank screen whe ...

Executing AJAX upon triggering the onchange event occurs prior to the full page loading

Let's paint the scenario. I have 2 dropdown menus. The first one triggers the onchange function which loads data into the second dropdown. It's functioning flawlessly, but I want to enhance it by loading data in the second dropdown using the onlo ...

Individual file for storing strings related to HTML content

Is there a method for organizing all constants in HTML (such as strings and numbers) into a separate file? Instead of <title>Hello World</title> could we do something like this instead? <title>STR_TITLE</title> and then, in ano ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

Utilize the Jest moduleNameMapper for locating files: "resolver": undefined

Among the various files I have, there is a text file located in the component directory within the path: src/components/text Despite this, Jest is unable to locate the file when utilizing the webpack alias import Text from "components/text"; I ...

I am having trouble with cookies, as I am unable to retrieve them from my localhost server

Currently, I am in the process of developing a user validation system for my application. However, I have encountered an issue with validating a token as it appears that the necessary cookie is not being retrieved from my browser's storage. Strangely, ...

The functionality of the JQuery $.post method may be compatible with Firefox but may encounter issues when

I've encountered an issue with my website where certain functions that update the database using $.post work perfectly in Firefox, but fail to function properly in Internet Explorer. I'm struggling to identify the root cause of this problem. Here ...

Utilize Bootstrap to align fields in the center

I'm new to using bootstrap and I could really use some help centering these text boxes and button. Any additional suggestions for improving the code would be greatly appreciated. My code is based on this template: https://github.com/BlackrockDigital/ ...

Is there a way to configure my dropdown menu so that only one dropdown can be open at a time and it remains open when clicking on a <li> item?

I've been working on developing a dropdown menu that appears when clicked, rather than hovered over. I've managed to implement this functionality using JavaScript, and overall, it's working quite well. Currently, the menu shows or hides whe ...

A guide on cropping and uploading images using ejs and Node.JS

Currently I am utilizing JQuery to crop an image. <link href="/public/css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" /> <!-- add scripts --> <script src="http://code.jquery.com/jquery-1.9.0.js"></script& ...

Implementing shallow routing with the Next.js 13 framework while having appDir functionality activated

Previously in Next 13 (or with appDir disabled), you could achieve the following: const MyComponent = () => { const router = useRouter(); const toggleStatic = () => { if (router.query.static) { router.push(router.pathname, router.pa ...