Fixing the error that occurs when selecting an option from a dropdown menu on

I am encountering an issue with my HTML form:

<form>
    <select>
        <option value="" selected>Select an option</option>
        <option  value="Warrior">Warrior</option>
        <option value="Paladin">Paladin</option>
        <option value="Mage">Mage</option>
        <option value="Shaman">Shaman</option>
        <option value="Warlock">Warlock</option><option value="Priest">Priest</option><option value="Druid">Druid</option><option value="Hunter">Hunter</option>
       <option value="Rogue">Rogue</option>
       </select>
    <p></p>
<br>
    Stamina
    <br>
    <input type="number" name="stamina" placeholder="0" />
<br>
<span id="staminaresult"></span>

The JavaScript function calculates a result based on the user input in the form but also requires selection from a dropdown menu:

$("form").on('keyup change', function (e){
    e.preventDefault();
    var selectedValue = $('select').val();
    var stamina = $('input[name=stamina]').val();

    if (!selectedValue) {
        return alert('You must choose your class');
    }

    stamina = stamina * 10;

    document.getElementById('staminaresult').innerHTML = ('+' + stamina + ' Hit Points')

When a user interacts with the form, they may encounter multiple error dialogs due to the .keyup function triggering unintentionally. How can I modify the code to prevent this?

For more details and context, refer to this jsfiddle link: https://jsfiddle.net/ejnLbyug/

Thank you, T

Answer №1

There is an issue with the handler attached to your problem:

$("form").on('keyup change', function (e){

This arrangement indicates that both the keyup and change events will trigger the listener. If a keyup event occurs and your alert pops up, focus will no longer be on the input, resulting in a change event from the input.

To resolve this, you can check if the event's target belongs to one of your numeric input fields and return immediately if it does and if the event was a change event:

$("form").on('change keyup', function (e){
  if (e.target.type === 'number' && e.type === 'change') {
    return;
  }

$("form").on('change keyup', function(e) {
  // Various calculations and assignments happening here based on user input
});

A more user-friendly approach would be to utilize a proper modal instead of using alert, which has usability issues like stealing focus and blocking interactions.

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

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

AngularJS view is not refreshing

I am facing an issue with updating a view via a controller that fetches data from a service. Despite changing the data in the service, the view does not reflect these updates. I have created a simplified example from my application, which can be found here ...

Step-by-Step Guide on Uploading a File with a Basic jQuery-AJAX Request

I'm in need of a straightforward client-side script for ajax file uploading. I searched the web for such a script, but all I found were plugins with numerous features. I just want a simple ajax file upload script. Is it possible to create something l ...

Utilize JavaScript to send login information to a website

I have a specific task in mind: creating a script that will automatically fill in certain data on an HTML website. To illustrate, let's imagine the site is the StackOverflow login page and I want to input my username and password. For the username fi ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...

Maximizing efficiency by utilizing factory or services to transfer data within AngularJS controllers

I am new to AngularJS and I am currently trying to understand how to push an array of objects data (not input strings) between controllers. Right now, my code is pushing the data into one controller ('ChooseTabCtrl') but I actually want it to go ...

I am struggling to comprehend the data organization illustrated by the typescript type declaration

type DocumentData = { [field: string]: any }; let data1: DocumentData = {4:3}; console.log(data1); //{4:3} It appears that the DocumentData type in the code above defines an object type where the key is of string type and the value can be of any type. Th ...

How can I omit a child element from a list of children using jQuery?

Within my website's structure, I have a parent div element with the ID #mmm-a that is initially set to be hidden using the CSS property visibility: hidden as a result of a previous onclick function. To make this parent div reappear when clicked, I am ...

Is there a dependable API available for capturing window screenshots using either JavaScript or PHP?

Would it be possible to capture a screenshot of window or div elements using JavaScript? I tried using "HTML5's CANVAS" but the quality of the result was not satisfactory. Is there a more reliable API available for this task? ...

The Ajax request functions flawlessly on Mozilla but encounters issues on Chrome, causing confusion as it occasionally works

I am using a PHP file with a class and function to store data in the database, accessed via AJAX. While everything works smoothly in Mozilla, Chrome seems to be causing some issues. Strangely, sometimes it works fine, but other times it fails for no appare ...

Generating npm package without including file extensions in imports

I am currently working on creating an internal library for my workplace. Everything seems to be going smoothly until I try to use it in another project. It appears that the file extension in all of the import statements has disappeared during the npm pack ...

Is it possible to activate the jQuery .click() function for a button with specific text?

Here's a dilemma I'm facing: $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s ...

I am currently working on a project using ar.js

I came across a glitch code that triggers a video when scanning the marker. However, I encountered an issue where it only works on desktop. On Chrome for Android, the video does not appear, only the sound can be heard. I need assistance as my coding knowle ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

What is preventing this JSON object from being parsed correctly?

Within my JavaScript file, The process of declaring and parsing the ajax response text is as follows: var subcats = JSON.parse(this.responseText); The actual responseText that needs to be parsed looks like this: {"presubcatId":"1","precatId":"1","presu ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...

Scrollbar not appearing when overflow-y is set in React Textarea Input on Chrome or Edge

I've been struggling to add a scrollbar to a React Textarea. I've referred to an old post on Stack Overflow here and a few other resources, but haven't had any luck. I've tested it in both Chrome (Version 113.0.5672.129) and Edge (Vers ...

Using JavaScript to invoke Applescript commands

Is it feasible to execute Applescript from JavaScript? I would be grateful if someone could offer a sample code or useful reference link. ...

Struggling to make Bootstrap-vue form validation functional

I am encountering an issue with form validation in Vue CLI and Bootstrap. When the page loads, all input fields show as invalid due to being assigned the is-invalid class. I managed to solve this problem by setting the state prop to null when it is false. ...