Utilize the keyboard's vertical arrows to adjust values as needed

Implement the functionality to increase and decrease the value in a label or p tags using the onkeydown and onkeyup events, without requiring a textbox input.

I have come across numerous examples, but they all rely on textboxes.

I am looking for a solution where I can increment the value by one (1,2,3,4...n) with each key press of (onkeyup or onkeyright), and decrement from (n...4,3,2,1) with each key press of (onkeydown or onkeyleft) on a label or p tag.

<input type="text" size="2" value="1" />


<script>
    var $label = $('label');
    $(document).on('keydown', function(event) {
        if (event.which == 38 || event.which == 104) {
            $label.text((parseInt($label.text()) + 1));
        } else if (event.which == 40 || event.which == 98) {
            $label.text((parseInt($label.text()) - 1));
        }
    });
    </script>

This code snippet works with textboxes. Can you suggest how I can adapt this for use with labels?

Answer №1

Check out this solution:

var $input = $('p');
$(document).on('keydown', function(event) {
    if (event.which == 38 || event.which == 104) {
        $input.text((parseInt($input.text()) + 1));
    } else if (event.which == 40 || event.which == 98) {
        $input.text((parseInt($input.text()) - 1));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="inputValue">0</p>

You were on the right track, but here are some tweaks I made to make it work:

  • Changed from using .val() to .text()
  • Switched from <input> to <p>
  • Adjusted variable $input to target <p>

If you want to utilize a <label> tag, simply update

  • var $input = $('p'); to var $input = $('label');
  • <p id="inputValue">0</p>
    to
    <label id="inputValue">0</label>

For example:

var $input = $('label');
$(document).on('keydown', function(event) {
    if (event.which == 38 || event.which == 104) {
        $input.text((parseInt($input.text()) + 1));
    } else if (event.which == 40 || event.which == 98) {
        $input.text((parseInt($input.text()) - 1));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="inputValue">0</label>

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

How can text be extracted from BeautifulSoup without displaying the opening tag and before the <br> tag?

I have recently started learning Python and Beautiful Soup, and I've spent a significant amount of time trying to solve this particular issue. I am looking to extract three specific text elements from a <div> that does not have a class attribu ...

Working with attributes in AngularJS directives

Building an overlay (or modal window) in AngularJS has been on my mind, and I've made some progress with the html/css layout. Here's a sneak peek at what it looks like: <section class="calendar"> <a open-overlay="overlay-new-calenda ...

Adjusting button alignment when resizing the browser

Is there a method to relocate buttons using Bootstrap 5 in HTML or CSS when the browser is resized? For instance, if the button is centered on a full-screen browser, but I want it at the bottom when resized. Is this achievable? ...

AngularJS Data Binding Issue - Watch cycle fails to trigger

View the JSFiddle example here: https://jsfiddle.net/pmgq00fm/1/ I am trying to achieve real-time updating of my NVD3 chart by utilizing the setInterval() function on line 39, which updates the data bound to the directive. Here is a brief overview of the ...

Can multiple links be hrefed at the same time?

On my website, I have a particular anchor tag that links to another page: <li><a class="dropdown-item" href="/<%= term._id %>"><%= term.term %></a></li> Now, I am looking to add an additional href li ...

How to isolate a function in React when mapping data

I am currently working on mapping data as a repeater in my React project. However, I am facing an issue with isolating the opening function, specifically with an accordion component. As I continue to learn React, I want to ensure that each accordion operat ...

Passing a variable by copy in a done call with Ajax

Here's the code snippet I'm working with: for (var i = 0; i < list.length; i++) { $.when( $.ajax({url: "./dorequest.php?id=" + list[i], success: function(response){ jsonFriendlist = response; }}) ).done( ...

django is not able to load staticfiles from the statifiles_dirs directory

I have placed my style.css in the directory appname/static/appname/. In my settings.py, this is what I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) When I try to load it in my base.html like t ...

Creating a JavaScript function that increments or decrements a variable based on keyboard input is a useful feature

My goal is to have a count start at 100 and then either count up or down by 1 when a specific keyboard button is pressed. Currently, I am using the keys 8 and 2 on the keypad, which represent ascii numbers 104 and 98. So far, the code I have only allows f ...

Allowing breaks with the :nth-child() selector

There must be a straightforward explanation for this perplexing issue. However, in my view, it ought to function as intended. We are currently utilizing the Bootstrap 3 CSS framework. The following code is present on a specific page: <div class="promo ...

When attempting to download a PDF file from Flask to the client, the file appears to be

I am encountering an issue with my Flask server that sends a PDF file using the send_file function. When testing this route on Postman, I am able to view and download the PDF successfully. However, when attempting to download it through my React frontend, ...

Error message: "An issue occurred: Unable to access undefined properties (specifically, borderRadius) in MUI react."

I recently created a navigation bar with an integrated search bar component. The styling for my search component was done using MUI styled from @emotion/styled in MUI library, where I applied a borderRadius: theme.shape.borderRadius. However, I encountere ...

The process of how screen readers interpret HTML elements

It is important to understand that screen readers not only read the content within elements and tags, but also the elements or tags themselves. For example: <button class="class-of-the-button">Text inside</button> When read by a screen reader ...

Retrieve data from a single PHP page and display it on another page

In my project, I am working with three PHP pages: index.php, fetch_data.php, and product_detail.php. The layout of my index.php consists of three columns: filter options, products panel, and detailed description. Whenever a user clicks on a product in th ...

"Utilize browser detection to direct users to appropriate pages - whether by using htaccess or another method

I'm in the process of creating a website and I've noticed that it looks quite bad on Firefox and IE. I was wondering if you could help me figure out how to redirect users to different pages based on the browser they are using. Since I am not an ...

Lazy Load immediately loads images that are visible on the screen without needing a click

I am facing an issue with Lazy Load on my image-heavy website. I want the images to load only when a button is clicked, but currently, it only partially works. Images below the fold follow the desired behavior of loading on click, but those above the fold ...

Animation in CSS3: Blinking overlay block

I am interested in creating an element that will overlay a section of a webpage using position: absolute. The element should be 50% opaque and blink between red and transparent, similar to the way OSX used to do with default dialog buttons. Is there a way ...

Displaying a ReactJS component inside a map function by giving it a unique identifier

When I click on a button within a .map function, I want only the component I clicked on to be displayed and not repeated in all the others. Currently, the behavior of the component is as follows. https://i.sstatic.net/FxsGC.png Clicking on the three dots ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

Troubleshooting: Custom icons not displaying in Next.js application

Every time I attempt to use icons that I have loaded into my source code, I keep getting this default icon displayed: https://i.sstatic.net/AWhcW.png I'm uncertain about what exactly is causing this issue. Here is the layout of my file tree for ref ...