The variable "input" was intended to hold the value entered into the input field, however, it is currently storing

Could you please take a look at the code provided below? The issue I am facing is that "The variable input is supposed to hold the value of an input field, but instead it ends up storing 'undefined'."

var input = $("#input-item").val();
var count = 0;
$(document).ready(function() {
$("#add-item").click(function() {

    if(input !== "" || input !== null) {
        $("#ulTodo").append("<li " + "name=li" + count + ">" + input + "</li>");
        count += 1;
    }

    else {
        return false;
    }
});
});

Answer №1

Issue : variable input is undefined

Resolution :

1) Make sure to assign a value to the variable inside the click event, as it is initially undefined

2) Use

var input = $("#input-item").val();
within the $("#add-item").click() function

Review the code snippet provided below:

var count = 0;
        
$(document).ready(function () {
    $("#add-item").click(function () {
        var input = $("#input-item").val();//assigning input variable within the click event
        if (input !== "" || input !== null) {
            $("#ulTodo").append("<li " + "name=li" + count + ">" + input + "</li>");
            count += 1;
        }
        else {
            return false;
        }
    });
});
p {
    margin-top:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="input-item" name="input-item" placeholder="add an item to the list...">
<button id="add-item">Add this item</button>

<p>Item list as below :</p>
<ul id="ulTodo">
    <li>this is item 1</li>
</ul>

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

The menu lacks responsiveness

I'm looking to create a responsive menu on my website where the button that opens the navigation will be hidden in "desktop mode". I came across some information on w3school, but I seem to have made an error. Can you assist me with this, please? Thank ...

How can you spot the conclusion of different lines that refuse to remain in place?

Currently, I am facing a jquery issue that has left me stumped. The website I am working on is structured as follows: <div class="Header"></div> <div class="main"><?php include('content.html'); ?></div> <div clas ...

Any suggestions on how to avoid code repetition using Jquery?

This code allows me to create a menu for my gallery. By setting the .masonry # elements to display:none, I can use the corresponding ID in the menu to show the correct gallery when clicked. However, there is a lot of repetitive code in this implementatio ...

PHP Verify that all variables contain no data

Looking for an efficient way to verify that all data submitted from a form to a PHP script is accurate. Code Snippet <?php $Name = $_POST['Name']; $ID = $_POST['ID']; $Submit = $_POST['submit']; $Reset = $_POST['rese ...

Unexpected problem with redrawing HTML application in Android WebView

I created a basic nixie clock app using HTML and wrapped it in a WebView for use on Android. It consists of one HTML file, a JS file, a CSS file, and ten digit images. After a few hours, I noticed stripes appearing in the center of the screen where the an ...

Implementing position sticky on a div depending on its content text - step by step guide

If the text inside the .newsDate matches the previous or next .newsDate, I want to make its position sticky when scrolling, until it reaches the next .newsMiddleCont div. What I'm trying to achieve: The same date on multiple news items should s ...

Labels can sometimes cause text input fields to become unresponsive

I've encountered a bug while working on my website with the materializecss framework. Sometimes, inputs are not responding correctly. This issue seems to occur when clicking on the first input and accidentally targeting the higher part of the second ...

Using Ajax to implement the Modal IF functionality

Currently in the process of registering a domain, utilizing two modals in the process. Through Ajax, I have set it up so that if the response is 1, an alert stating that the domain is available is displayed. If the response is 0, an alert stating that the ...

To retrieve data from an AJAX response, you will receive an array in the form of a string

After requesting a list of posts submitted by users from my server, the response I received was a string containing an array of stdClass objects. If it had been an actual array, that would not have been an issue. However, it arrives as a string in the foll ...

Displaying modal popups limited to one per session

Is there a way to display this Dialog Popup only once per session? I have looked into using cookies for configuration, but haven't been able to implement it in this scenario: $(document).ready(function() { ShowDialog(true); e. ...

Does the functionality of JSON.parse include recursion?

After receiving a JSON string in response, I parse it as follows: ring = JSON.parse(response); However, although ring becomes an object, the property ring.stones is only a string when it should also be an object. To address this issue, if I execute: ri ...

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Loading pages asynchronously using Ajax with added interactivity through custom JavaScript scripts

Using jQuery Masonry in conjunction with another JavaScript for voting, here is the code: <div id="contain"> <?php $result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); while($row = mysqli_fetch_array($result ...

The collapsible feature seems to be malfunctioning in Bootstrap

I attempted to create a button using Bootstrap that would reveal hidden content when clicked, but it doesn't seem to be working. Any suggestions or advice on how to make it function properly? <button class="bc2 border-primary bg-primary rounde ...

Exploring the possibilities of personalized attributes/directives in HTML and Javascript

My current challenge involves understanding how vue.js and angular.js handle custom directives in HTML. Suppose I have a div like this: <div my-repeat="item in items"></div> To replicate the functionality of vue.js, do I need to search throug ...

What is the method to modify the text of an element without altering its existing properties?

https://i.stack.imgur.com/cBu6P.png $.ajax({ type: "GET", url: "my url" + x, datatype: "html", success: function(data){ //alert(x); //var Content = data; var sendId ; var data = $.parseJSON(data); ...

HTML Button without Connection to Javascript

When attempting an HTML integration with GAS, the code provided seems to be generating a blank form upon clicking "Add" instead of functioning as expected: //GLOBALS let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = ss.getLa ...

The disappearance of the final element in an array after adding a new one using JavaScript

One of the challenges I'm facing in my backbone project involves creating an Add To Cart feature using window.localStorage. Below is my javascript code for the addToCart() function: var cartLS = window.localStorage.getItem("Cart"); var cartObject = ...

When I choose an option from the dropdown list, the check boxes become disabled

I need help in disabling multiple checkboxes when a particular option is selected from a dropdown list, using JavaScript. The code snippet I currently have is not the best approach as it disables all fields. function disableFields(select) { if(datatype ...

Sharing information across various web pages

Struggling with PHP as a beginner. Currently using HTML5, CSS3, jQuery, and Bootstrap 4. I have 4 HTML pages on my site. The first page displays 4 squares labeled A, B, C, and D. Users select one square and click "Next" to proceed to page 2. Page 2 must ...