Tips for extracting value from a chosen input field without relying on its unique identifier

I am working on a simple code to help guess notes by ear. The concept involves tabs with empty input fields where numbers need to be entered based on a specific melody for the guitar fretboard. One button reveals the first note, while another button checks if the correct number has been entered and either approves or erases it accordingly.

I have been able to check each input field using its id, but I am wondering if there is a way to retrieve the value from the selected input when the second button is pressed and compare it to the placeholder or value attribute?

If you would like to view my progress, here is the link to my Codepen page: https://codepen.io/fukenist/pen/BxJRwW Here is the script part:

function showfirst() {
    document.getElementById("fst").value = "12" 
}
function show1other() {
    var snote = document.getElementById("scnd").value;
    if (snote == 9 ){
        document.getElementById("scnd").value = "9";
    }
    else {
        document.getElementById("scnd").value = "";
    }
}

Answer №1

You can iterate through all your input elements using document.querySelectorAll().

Here is a sample code snippet:

// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');

// Function to reveal the first input's value
function showFirst(){
  inputs[0].value = inputs[0].dataset.v;
}

// Function to check all values and clear input if incorrect
function checkAll(){
  inputs.forEach(function(input){
    if(input.dataset.v !== input.value){
      // Incorrect answer, clear input
      input.value = '';
    }
  });
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>

Additional Notes:

  1. I opted to use data-v instead of placeholder to store the correct answers due to semantic differences.
  2. If you find manually transcribing songs laborious, consider utilizing a JSON string or another method to map out tabs alongside a templating system for alignment. Consider aspects like note alignment, song timing, and special moves such as slides or hammer ons.
  3. To maintain alignment consistency, background Guitar Strings could be considered an option either as a background-image or absolutely positioned overlapping divs.

For further information:

HTMLElement.dataset

document.querySelectorAll

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

Adjusting the height of a Vue component to 100% triggers a change in height whenever a re-render occurs

In my Vue component, there is a class called "tab-body-wrapper" that serves the purpose of displaying the "slot" for the active tab. However, I encountered an issue while troubleshooting where the height of the ".tab-body-wrapper" component reduces during ...

The integration of Google Translate with Javascript on HtmlEditorExtender is experiencing difficulties and is not functioning properly

I implemented the use of a text box with ajaxtoolkit HtmlEditorExtender (Rich textbox) to translate English to Gujarati using Google translation Javascript. The translation function works perfectly with the regular text box, but encounters issues when used ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

updating dropdown options based on user input with PHP

I need help with implementing a code for two dropdown boxes. The first dropdown should display main category values dynamically, and when a value is selected, the second dropdown should appear with corresponding sub-category values. How can I achieve this ...

In what time frame is Javascript/AJAX functioning?

Do you know if the times are measured in milliseconds or seconds? I'm puzzled why these two scripts aren't synchronizing - there's a significant delay. $(document).ready(function() { $("#idle").delay(300000).fadeIn(500); }); var interv ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

Is it more efficient to have a single global event listener or multiple event listeners of the same type in each component for productivity?

This particular mixin is a key component in numerous pages, often appearing in multiple sections within the page. data: () => ({ device: { mobile: false, tablet: false, tabletLand: false, notepad: false deskto ...

What is the significance of the error message "react/jsx-no-undef" when it says "'Input' is not defined"?

Can someone help me figure out why I'm getting 'Input' is not defined react/jsx-no-undef error in my code when trying to create an input field for name? The form with textarea is working fine. I will be passing the name into my dispatch fun ...

What is the process for creating a widget that can be seamlessly integrated into someone’s website and hosted on your own site

In relation to this previous question. After researching JSONP and conducting some tests, I've realized that I am completely clueless about what I'm doing... What is required? I am developing a customer service tool for people to integrate in ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

The issue code R10, indicating a boot timeout, has arisen as the web process failed to connect to $PORT within 60 seconds of initiating on Heroku platform

After deploying my Node.js WebApp to Heroku, I encountered the following error: 2021-06-01T09:19:42.615419+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-01T09:19:47.259832+00:00 heroku[web.1]: Starting process with command `node app.j ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

Change HTML canvas data into Angular form data before sending it to the Laravel backend

My JavaScript code to convert a data URL to blob and send it as a form request is: var canv = document.getElementById("mainCanvas"); var dataURL = canv.toDataURL('image/jpg'); documentData = {"image": dataURLtoBlob(dataURL), "gameName": "empero ...

Challenges arise when utilizing the foundation 6 grid for image overlays within a React application

Having some trouble using the foundation 6 xy grid for the first time and aligning three images with text overlays at the bottom of each image. I am struggling to make the background of the text fill the full width of the image while also ensuring it is re ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this? I attempted to use addEventListener('click', myFunction) on `document` but it did not w ...

Reconfigure the API to segment its components into individual variables

I'm currently working with an API that offers a wide range of available calls. In my VUE code, I am looking to modify it so that depending on which button is clicked, a different call is triggered. You can check out one example of this here: <> ...

Error encountered while attempting to generate migration in TypeORM entity

In my project, I have a simple entity named Picture.ts which contains the following: const { Entity, PrimaryGeneratedColumn, Column } = require("typeorm"); @Entity() export class Picture { @PrimaryGeneratedColumn() ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

Tips for creating a tooltip above an SVG circle with AngularJS

I'm currently working on a project where I am using AngularJS and SVG to plot circles on a page. My goal is to have a tooltip appear when a user hovers over one of the circles. I came across an explanation on how to achieve this on this website, but u ...