What could be causing the disappearance of the value I'm trying to add to an unordered list immediately after I add it?

Is there a way to transfer the content of a "text box" to an unordered list when the user presses the "Enter" key?

This is the HTML structure:

<input type="text" name="InputUPC" id="InputUPC" />
<ul id="CandidateUPCs" name="CandidateUPCs" class="ulUPCs"></ul>

CSS styling for the unordered list:

.ulUPCs {
    min-height:160px;
    height:auto !important;
    height:160px;
    max-width:344px;
    width:auto !important;
    width:344px;
    border-style:solid;
    border-width:2px;
}

The jQuery code to handle keypress event:

$('#InputUPC').keypress(function (event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        var upcPrefix = jQuery.trim($("#InputUPC").val());

        if (upcPrefix != "") {
              $("#CandidateUPCs").append('<li>' + upcPrefix + '</li>');
        }
        $("#InputUPC").val("");
    }
});

However, after entering a value in "InputUPC" and pressing Enter, the value briefly appears in the list but then disappears. The input field gets cleared as expected, but why does the value vanish from the list too?

UPDATE

I made some changes based on adeneo's answer and here's the updated code snippet (http://jsfiddle.net/AEy9x/):

$('#InputUPC').keyup(function (event) {
    event.preventDefault();
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        var upcPrefix = jQuery.trim($("#InputUPC").val());

        if (upcPrefix != "") {
              $("#CandidateUPCs").append('<label for=' + upcPrefix + '>' + upcPrefix + ' </label>');
              $("#CandidateUPCs").append('<input type=\"checkbox\" name=' + upcPrefix + ' id=' + upcPrefix + ' />');
              $("#CandidateUPCs").append('<br>');
        }
        $("#InputUPC").val("");
    }
});

UPDATE 2

The code works with jQuery versions above 1.6.4. I upgraded to jquery 1.9.1, but it still doesn't work as expected.

Even though I updated jquery-ui as well:

@*    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.16.custom.min.js")" type="text/javascript"> </script>*@
    <script src="@Url.Content("http://code.jquery.com/ui/1.10.3/jquery-ui.js")" type="text/javascript"> </script>

UPDATE 3

The issue persists with either block of code (first mine, second adeneo's). The content flashes in the UL momentarily and then disappears quickly.

 
// Your code block
$('#InputUPC').keyup(function (event) {
    event.preventDefault();
    var keycode = (event.keyCode ? event.keyCode : event.which);
    // Rest of your code
);

// Adeneo's code block
$('#InputUPC').on('keyup', function(e) {
e.preventDefault();
if (e.which == 13) {
    var upcPrefix = $.trim( this.value );
    // Rest of the code
}

UPDATE 4

The form is being submitted even though preventDefault has been used. This can be observed when checkboxes get deselected along with the brief appearance and disappearance of values in the UL.

Is there something like this meta-metaphor that could solve the issue?:

e.preventDefault(); ! important

UPDATE 5

The problem persists despite including these modifications:


$('#InputUPC').keyup(function (event) {
    if (event.stopPropagation) { // W3C/addEventListener()
        event.stopPropagation();
    } else { // Older IE.
        event.cancelBubble = true;
}
         event.preventDefault();
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            var upcPrefix = jQuery.trim($("#InputUPC").val());

            if (upcPrefix != "") {
                  $("#CandidateUPCs").append('<label for=' + upcPrefix + '>' + upcPrefix + ' </label>');
                  $("#CandidateUPCs").append('<input type=\"checkbox\" name=' + upcPrefix + ' id=' + upcPrefix + ' />');
                  $("#CandidateUPCs").append('<br>');
            }
            $("#InputUPC").val("");
        }
    });

Answer №1

$('#InputUPC').on('keypress', function(e) {
    e.preventDefault();
    if (e.keyCode == 13) {
        var inputText = $.trim( this.value );

        if (inputText != "") {
              var newElement = $('<li />', {text : inputText});
              $("#ListItems").append(newElement);
        }
        this.value = "";
    }
});

Answer №2

The functionality in the original code seems to be working correctly, however it is worth noting that if the input element is contained within a form in your actual implementation, pressing the enter key may trigger form submission (refer to §4.10.22.2 "Implicit submission" in the spec). This behavior you are observing is not caused by a bug in your script but rather due to the page refreshing.

To address this issue, you can include: [event object].preventDefault();

Check out these examples:

  1. Unwanted form submission
  2. Resolved

Answer №3

Adeneo's solution is correct. However, if you prefer to make it function without updating to jQuery 1.9, you have the option of using the "bind" event instead of "on". The "on" event is compatible from version 1.7 and onwards, replacing the older "bind" method in newer versions.

$('#InputUPC').bind('keyup', function(e) {

Answer №4

UPDATE 4 In this case, the form is still submitting despite having code in place to prevent it (preventDefault). This is evident when multiple checkboxes are selected and then suddenly deselected at the same time as any input briefly entered into the UL disappears. It seems like there might be a need for something similar to the following combination:

e.preventDefault(); ! important?

The issue you're facing could be due to event bubbling. To address this, try adding the following code snippet before using event.preventDefault();

if (event.stopPropagation) { // W3C/addEventListener()
        event.stopPropagation();
    } else { // Older IE.
        event.cancelBubble = true;
}

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

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

Apply a unique CSS class to the first two elements, then skip the following two elements, and continue this pattern using ngFor in Angular and flex styling

Here is a code snippet that displays a list of products using *ngFor in Angular: <div class="container-products"> <div class="item-product" *ngFor="let product of ['product A', 'product B', 'prod ...

An issue with HTML5 canvas arcs: distortion occurs in the arc shape

Below is the code I'm using to create an arc on an HTML5 canvas. <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="1000" height="550" style="padding-top:20px;border:1px solid #d3d3d3;"> Your browser does not support t ...

What is the most efficient way to utilize Promise.all in conjunction with React-Redux-Thunk?

export const FETCH_DB_BEGIN = 'FETCH_DB_BEGIN' export const FETCH_DB_SUCCESS = 'FETCH_DB_SUCCESS' export const FETCH_DB_FAILURE = 'FETCH_DB_FAILURE' export const fetchDatabase = () => { return dispatch => { ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

Selectize-dropdown menu shines brightly as it opens upwards

In my sleek dashboard design, I have implemented a few dropdown menus using selectizeInput. These menus are currently positioned at the bottom of the page, but I want them to open in an upward direction instead of downward. While I found a workaround for ...

The logo in the navigation bar fails to respond on a specific webpage with a background animation in progress

I've encountered an issue with a clickable logo on my website's navigation bar. The logo works fine on every page except the final page of my javascript quiz, where there's a background animation playing. I've tried adjusting the z-inde ...

What is the best way to determine which function to invoke in ngIf?

Depending on the value of a variable, I need to call either the login() or logout() methods from this.loggedInService.isLoggedIn. If the value of the variable is !this.loggedInService.isLoggedIn, then call login(). If !this.loggedInService.isLoggedIn is ...

The curious case of Jade view caching in Express

Recently, I updated my Node.js and Express to versions 0.10.21 and 3.4.4, respectively, and now I'm encountering some strange view caching issues during development (as well as production). It appears that the HTML generated from views included withi ...

Challenges with displaying content in Bootstrap tabs

I am currently working on the following code: HTML <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs" role="tablist" id="tabs_list"> <li class="nav-item"> <a class="nav-li ...

Prevent background element from being selected with a double-click

Whenever I double-click on the background, the first element gets selected. How can I prevent this from happening? Here is a fiddle to demonstrate: https://jsfiddle.net/cb6fjr7n/1/ <input style="text" value="lala"/> If you double-click outside of ...

Manipulating nested arrays using index values in JavaScript

Can someone assist me in sorting a multidimensional array based on the value of the first index? I've tried using a for loop without success. Looking for solutions in JS or jQuery. I want to convert the following array: var pinData = [ ['< ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

Obtain the $httpProvider from jQuery in order to intercept and manipulate messages

I am working on an Angular application that utilizes third-party JavaScript code, which I cannot modify. My goal is to intercept the HTTP messages from outside of Angular. I have managed to access the controller and injector, and retrieve the $http servic ...

What is the title of this particular CSS method?

I've been implementing a unique approach for more than a year now, and I have yet to come across similar practices elsewhere. Essentially, I am structuring display "states" or "modes" by utilizing CSS classes. Despite searching for terms like "css mod ...

Monitor the onBlur event exclusively on the Parent Div

Currently, I am in the process of developing a customized dropdown control for my application, and I have specific requirements to meet. Primary Action: When the user clicks on the textbox, a div opens up with a list of items that they can select from. Th ...

Having trouble with uploading image files in Laravel Vue.js?

I have been trying to upload my image file to a storage folder using Laravel and Vue.js. However, when I try to print the data using dd();, I get no response or error. How can I tell if I am doing it correctly? I suspect the error lies in the formData whe ...

Retrieve the data-id using ajax and send it to php on the current page

I need assistance in retrieving data-id using AJAX and passing it to PHP on the same page. I have a button set up, but when I try to echo $_POST["postid"], nothing seems to be happening. Can someone please help me identify any mistakes? I am new to worki ...

Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure: parent -> child -> secondChild Currently, there is a variable called isActive in the parent component. Below is how it can be implemented: paren ...