Include user input to an array in Javascript

I have a code snippet that allows users to enter words into an input box and store them in an array by clicking the Add Word button. Once multiple words have been entered, users can click the Process Word button to display all the words from the array. I need help with implementing this functionality efficiently. Additionally, I'm curious why the message "Field is empty" doesn't appear when nothing is entered in the input box.

function begin() {
var word = "List of words";
  var i = returnword.length

if (userinput.length === 0) {
word = "Field is empty"

}
  document.getElementById('message2').innerHTML = word
  while (i--) {



   document.getElementById('message').innerHTML = returnword[i] + "<br/>" +     document.getElementById('message').innerHTML;


}
}

 function addword() {
  var arrword = [];
  returnword = document.getElementById('userinput').value;
  arrword.push(returnword);
}

Answer №1

  1. Implement addWord() function

The function should include an array arrword. It is important to declare this array outside the function so that it retains its values between function calls.

  1. Dealing with empty input

If the user clicks on the Add word button without entering any text, a message for empty input should be displayed. Ensure to check the input field and handle empty inputs appropriately.

  1. Displaying words in the array

To display the words stored in the array, you can utilize the join() method.

var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');

function addWord() {
  errorElement.innerHTML = "";
  var word = inputElement.value;
  if (word.trim() === "")
    errorElement.innerHTML = "Empty input";
  else
    arrayOfWord.push(word);
  inputElement.value = "";  
}

function process(){
  words.innerHTML = arrayOfWord.join(' - ');
}
#error {
  color: tomato;
}

#words {
  color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>

Answer №2

Enhance your code with jQuery for a smoother experience! :)

If you choose to work with input using jQuery, consider the following approach:

var wordArray = [] // array to store words

/* Adding a click event listener to your "Add Word" button to
trigger the function when clicked by the user */
$("#addWordButtonID").on("click", function () {
  var wordEntered = $('#textInputID').val() // variable to capture user input

  if (wordEntered.length !== 0) { // condition to check if input is not empty
    wordArray.push(wordEntered)  // adding typed word to the array
  }
})

To include jQuery in your HTML page, simply insert

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in the header section of your HTML file

Answer №3

Make sure your HTML is correct before proceeding with the script adjustments:

<script>
    var arrword = [];
    var returnword;

    function begin() {
        var word = "List of words";
        var i = arrword.length;

        if (arrword.length === 0) {
            word = "Field is empty";
        }

        document.getElementById('message2').innerHTML = word;
        while (i--) {
            document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
        }
    }

    function addword() {
        returnword = document.getElementById('userinput').value;
        arrword.push(returnword);
    }
</script>


var arrword = [];
var returnword;

function begin() {
    var word = "List of words";
    var i = arrword.length;

    if (arrword.length === 0) {
        word = "Field is empty";
    }

    document.getElementById('message2').innerHTML = word;
    while (i--) {
        document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
    }
}

function addword() {
    returnword = document.getElementById('userinput').value;
    arrword.push(returnword);
}

<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">Process Words</button>
<input type="text" id="userinput" value="" />
<div id="message2">
    
</div>
<div id="message">

</div>


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

What is the best MySQL data type for storing JavaScript code with PHP?

I am creating a platform that resembles jsfiddle, allowing users to store their JavaScript codes and retrieve them in an organized manner. I am unsure about which data type would be most suitable for saving the codes, or if storing them in text files wou ...

Using DataTable with backend processing

Has anyone successfully implemented pagination in DataTable to dynamically generate the lengthMenu (Showing 1 to 10 of 57 entries) and only load data when the next page is clicked? I'm currently facing this challenge and would appreciate some guidance ...

Error: The URI you are trying to access is restricted and access has been denied

I'm facing an issue with my HTML file that contains multiple d3-graphs embedded directly within script tags. When I try to move one of the graphs to an external JavaScript file, I receive the following error message: "NS_ERROR_DOM_BAD_URI: Access to r ...

The Highcharts Angular Chart fails to update after the renderer.button event is triggered

Within the chart interface, you'll find two unique buttons designed to facilitate the updating of the series and redrawing of the chart based on user preference. One allows for toggling views by percentage, while the other does so by count. When the c ...

Data not being properly set in the form

Check out this chunk of HTML code: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> function getCords(){ ...

Switch out the second to last symbol

Is there a way to delete the second-to-last character from a string? For instance string = '96+658-+';<br /> fixInput(string); function fixInput(string) { // string= string.replace(/[-+xá]$/,''); // incorrect // string= ...

What is the best way to bring my file into app.js using JavaScript?

I've been attempting to include a JavaScript file into app.js within the create-react-app package. I tried the following code to import my file: Just a heads up: my file is located in a folder called components within the Navigation folder. import s ...

Attempting to load an image through an AJAX Request may prove to be unsuccessful

I am facing an issue with using an AJAX request to load a gif image from the following source: Despite my attempts, using the response on the image source like this: $('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + d ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

Angular $http.get: How to handle errors effectively?

When sending a form to Node.js for authentication, I am using $http.get in the following function and adding a promise with .then. Will this handle all possible errors that may occur from the server in production? Is there anything else I need to include i ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Using jQuery with multiple selectors can become tricky when dealing with elements that may or may not be present

I decided to be more efficient by using multiple selectors instead of rewriting the same code repeatedly. Typically, if one element exists then the others do not. $('form#post, form#edit, form#quickpostform').submit( function() { ...

Utilize the table's checkboxes to select recipients for mail distribution

I am working with a database table structure like this: ID email After fetching data from the database, I display it in an html table: <?php $sql = $link->query("SELECT ..."); while($data = $sql->fetch_object){ ?> <table> < ...

Is there a specific plugin that enables dynamic calculations within a django formset?

Looking for a solution: Is there a jQuery plugin available that can perform calculations for a Django formset? The form is dynamic, changing the ID of each field per row whenever the add button is clicked. ...

"Utilize JavaScript for graceful error handling in your project with

I am trying to implement an Ant task that involves adding JavaScript code. I want the success or failure of the target to be determined by the results of some logic executed in the JavaScript: <target name="analyze"> <script language="javas ...

Using AngularJS to prevent HTML injection in input fields

Is there an effective method to prevent HTML injection in input fields? As an example, if I have a search input field: <input id="search" type="text" ng-model="search" placeholder="search..."> I want to ensure that any attempts to input malicious c ...

Safari experiencing sporadic issues with reCAPTCHA AJAX API within modal dialogs

I am currently utilizing the reCAPTCHA AJAX API to showcase the captcha in a modal dialog box. To display the boxes, I am incorporating jqModal, and opting for the AJAX version of reCAPTCHA due to compatibility issues with the PHP version when used with jq ...

Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my ...

Javascript - Execute function after all nested forEach loops have finished running

I'm finding this task to be quite challenging, as I am struggling to comprehend it fully at the moment. The issue involves nested forEach loops, and I require a callback function to execute once all the loops have finished running. I am considering u ...

When handling a document click event in Typescript, an error may occur where it cannot read

Just starting out with Typescript and diving into Angular, I am currently in the process of converting my project to the Angular system. However, I've hit a roadblock. I need to figure out how to close the dropdown content when the user clicks anywher ...