Updating an HTML input field property with JavaScript is not reflecting the changes

I am currently working on a form with two fields: stationery type and stationery request quantity. The stationery request quantity field only accepts numerical input. The minimum quantity that can be entered in this field depends on the value selected in the stationery type field. For example, if "pencil" is chosen as the stationery type, then the minimum quantity allowed should be 5. If "notepad" is selected, then the minimum quantity should be 10. I have implemented some code to handle this logic, but it seems to be malfunctioning as it always defaults to the quantity specified for the first stationery type option.

To view the implementation and the issue, you can check out the jsfiddle here.

function random() {
                    document.querySelector('[name="stationerytype[]"]').value = ""
  
                    var a = document.getElementById('purpose').value;
                    if (a === "Meeting") {
                    var datalist = "datalist1";
                    } else if (a === "Departmental") {
                    var datalist = "datalist2";
                    }
    
                    document.querySelector('[name="stationerytype[]"]').setAttribute("list", datalist)

                    }

          var options = document.querySelectorAll(".option1");
            options.forEach(function(option) {
              option.addEventListener("keyup", function() {
                calculatingMinimumQuantity(option);
              });
              option.nextElementSibling.addEventListener('change', evt => {
                if (+evt.target.value < +evt.target.min) evt.target.value = evt.target.min
              });
            });
            
            function calculatingMinimumQuantity(option) {
              var minimum = 0, step1 = 0;
              var value = option.value;
              if (value === "PENCIL") {
                minimum = "5";
                step1="5";
              } else if (value === "NOTEPAD") {
                minimum = "10";
                step1="10";
              }
              //   getting the quantity input field
              option.nextElementSibling.setAttribute("min", minimum);
              option.nextElementSibling.setAttribute("step", step1);
              
        }
<div class="col-sm-6">
                    <label for="purpose">Purpose</label>
                    <select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required />
                    <option ></option>
                    <option value="Meeting">Meeting</option>
                    <option value="Departmental">Departmental</option>
                    </select>
                    </div>
                  
        <td><input  type="text" name="stationerytype[]" id="stationerytype" class="option1 form-control" autocomplete="off"  required>
                <datalist id="datalist1" >
                <option value=""></option>
                <option value="MEETING PEN">MEETING PEN</option>
                <option value="NOTEPAD">NOTEPAD</option>
                <option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
                <option value="PENCIL">PENCIL</option>
                </datalist> 
                
                <datalist id="datalist2" >
                <option value=""></option>
                <option value="A4 GREEN REAM">A4 GREEN REAM</option>
                <option value="A4 WHITE REAM">A4 WHITE REAM</option>
                <option value="BMO LETTER HEAD">BMO LETTER HEAD</option>
                </datalist>
          </td>
                            
                    
                            
        <td><input type="NUMBER" name="stationeryqtyrqst[]" id="stationeryqtyrqst" class="form-control" required ></td>

Answer №1

When trying to access the nextSibling element of the option in a JavaScript function, make sure the correct element is selected. If you are working with a td element, remember to reference the parent table element for proper functionality.

Here is an updated version of the HTML and JS code to meet your needs:

<div class="col-sm-6">
  <label for="purpose">Purpose</label>
  <select type="text" name="purpose" id="purpose" class="form-control" onchange="random()" required />
    <option ></option>
    <option value="Meeting">Meeting</option>
    <option value="Departmental">Departmental</option>
  </select>
</div>
                    
<table>
  <tbody>
    <tr>             
      <td><input  type="text" name="stationerytype[]" id="stationerytype" class="option1 form-control" autocomplete="off"  required>
        <datalist id="datalist1" >
          <option value=""></option>
          <option value="MEETING PEN">MEETING PEN</option>
          <option value="NOTEPAD">NOTEPAD</option>
          <option value="PLASTIC FOLDER">PLASTIC FOLDER</option>
          <option value="PENCIL">PENCIL</option>
        </datalist> 

        <datalist id="datalist2" >
          <option value=""></option>
          <option value="A4 GREEN REAM">A4 GREEN REAM</option>
          <option value="A4 WHITE REAM">A4 WHITE REAM</option>
          <option value="BMO LETTER HEAD">BMO LETTER HEAD</option>
        </datalist>
      </td>   
      <td><input type="NUMBER" name="stationeryqtyrqst[]" id="stationeryqtyrqst" class="form-control" required ></td>
    </tr>
  </tbody>
</table>

Below is the revised JS code:

function random() {
                    document.querySelector('[name="stationerytype[]"]').value = ""
  
                    var selection = document.getElementById('purpose').value;
                    var datalist;
                    if (selection === "Meeting") {
                      datalist = "datalist1";
                    } else if (selection === "Departmental") {
                      datalist = "datalist2";
                    }
    
                    document.querySelector('[name="stationerytype[]"]').setAttribute("list", datalist);

                  }

var options = document.querySelectorAll(".option1");
options.forEach(function(option) {
  option.addEventListener("keyup", function() {
    calculatingMinimumQuantity(option);
  });
  option.nextElementSibling.addEventListener('change', evt => {
    if (+evt.target.value < +evt.target.min) evt.target.value = evt.target.min;
  });
});

function calculatingMinimumQuantity(option) {
  var minimum = 0, step = 0;
  var value = option.value;
  if (value === "PENCIL") {
    minimum = "5";
    step = "5";
  } else if (value === "NOTEPAD") {
    minimum = "10";
    step = "10";
  }
              
  // Update quantity input field attributes
  option.parentNode.nextElementSibling.firstChild.setAttribute("min", minimum);
  option.parentNode.nextElementSibling.firstChild.setAttribute("step", step);
}

Answer №2

Instead of using option.nextElementSibling to reference the element with id stationeryqtyrqst, you are actually pointing to a datalist with id datalist1. To fix this, you should use document.getElementById like so:

function calculateMinimumQuantity(option) {

        var minimum = 0, step = 0;
        var value = option.value;
        if (value === "PENCIL") {
            minimum = "5";
            step = "5";
        } else if (value === "NOTEPAD") {
            minimum = "10";
            step = "10";
        }
        // get the quantity input field
        var stationeryQtyRequest = document.getElementById("stationeryqtyrqst");
        stationeryQtyRequest.setAttribute("min", minimum);
        stationeryQtyRequest.setAttribute("step", step);

    }

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

Guide on implementing gradient animation effects in a React component

How can I implement gradient animation effects like this example in a React component using inline CSS? I need to utilize the CSS-based gradient animation effects shown below directly within the React component. Are there any specific packages available ...

What is the best method for deleting scripts to optimize for mobile responsiveness?

My current plugin.js file houses all my plugins for responsive design, but it is unnecessarily large and cumbersome for mobile devices. I am considering creating two separate plugin.js files to toggle between for mobile and desktop views. What are the r ...

Activate Google Map marker through an external click

I need help with implementing anchor buttons for different locations that highlight the location details on click. For example, when clicking on "location1" button, I want to highlight location1 on Google Maps. Check out the demo on JSFiddle google.maps.e ...

Webpack is having trouble locating images within Nextjs

When I import static images with no issues using npm run dev, everything runs smoothly. However, when attempting to utilize npm run build or next build, it fails and prevents deployment to Vercel. next info Operating System: Platform: win32 ...

Trouble arising from Bootstrap 5's float-end on flex items

When I apply the float-end class, it shifts the button to the right, but the div tags next to it appear in front of it. https://i.sstatic.net/Mxu0P.png <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protecti ...

Exploring the ways to retrieve the returned Dynamic scope in AngularJS

There's a specific need I have - I require a single AngularJS function that can dynamically return the scope variable based on an input parameter. When it comes to controller functions, I've come across examples of how to achieve this dynamic sco ...

Issue encountered: "require" is not recognized when attempting to access my local JSON file in Vue.js

I am venturing into the world of vuejs... I attempted to retrieve data from my JSON file stored locally, but the decision on which specific JSON file's data to fetch is dynamic. I keep encountering an error stating 'require' is not define ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

appear on the screen of a Samsung smart television

Can anyone offer some assistance? I am currently working on this in JavaScript. $('#popup').sfPopup({ text: 'Would You like to close this popup?', buttons: ['Yes', 'No'], defaultFocus: 1, ...

Can we enhance the efficiency of this equation?

The formula provided organizes the elements in the container based on mouse movement. The issue stemmed from the image size and the different calculations performed when approaching along the x and y axes from various directions. const zoomEffect = (even ...

Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items. The final JSON output should be sorted by the attribute 'name&apos ...

Ways to evenly distribute divs into rows

Greetings if this question has already been inquired about, but my search turned up nothing quite like it. My current setup is as follows: .main{ display: inline-flex; flex-direction: row; } <div class = "main"> <div class="sub-div ...

Inject HTML entities, escaped for CSS, dynamically using JavaScript

My goal is to dynamically generate a list of HTMLElements with unique data-* attributes that correspond to various HTML Entities. These attributes will then be utilized by CSS to display content in pseudo elements like this: li:after { content: attr(dat ...

What causes my code to break completely when I import something?

My chrome extension has a simple function that retrieves a user's selected text using the Chrome Tabs API. I am looking to integrate a Hugging Face API in the future, but I am facing an issue. Whenever I try to import the necessary model, the Chrome T ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Using PHP to calculate the total number of records within an HTML document

I am currently working on a PHP script to establish a connection with my MySQL database in order to retrieve the total number of users registered on my forum by counting the records in the table. https://i.sstatic.net/ZR0IY.png The PHP script should disp ...

Resize a container to match the height of either its children or the full height of the window

I'm seeking advice on how to properly use height: 100%. Is there a way to scale a div based on the height of the window and its content simultaneously? I want one to override the other if necessary. Here's an example of standard height 100% css ...

Utilizing useState for React Data Picker

I recently attempted to implement the React Data Picker in my React project using npmjs. However, I encountered an issue when trying to import useState from import React, { useState } from "react"; The error message displayed: 'useState&a ...

A guide to duplicating the Mesh of a Line entity using THREE.js

I am attempting to create a for loop consisting of 10 lines. However, I am encountering an error with line.Clone() as it is unable to find any mesh to clone from. If you have any insights on how to access the mesh of a line, please share. Below is the cod ...