Sergio Iliev
Sergio Iliev

Reputation: 81

How to get value from selected input field (not using id)

I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.

I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?

It is my codepen https://codepen.io/fukenist/pen/BxJRwW 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 = "";
    }
  }

Upvotes: 1

Views: 56

Answers (1)

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

You can use document.querySelectorAll() to get all your inputs and loop over them.

Sample:

// 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 wrong
function checkAll(){
  inputs.forEach(function(input){
    if(input.dataset.v !== input.value){
      // Wrong 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>

Notes:

  1. I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
  2. It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
  3. It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)

Reference:

HTMLElement.dataset

document.querySelectorAll

Upvotes: 1

Related Questions