简体   繁体   中英

How to create flexible input-fields in Javascript?

I am having problems to create the following situation:

I want to create inputfields, where I can write "1", "2" or "3" in any order, but each number is only allowed to be writen once.

Repeating one of those three numbers and writing other numbers than those three in the inputfields should be considered bad.

What do I need to add to the code?

 a = 1 b = 2 c = 3 L = a L = b L = c function F1() { feedBack = document.getElementById("feedBack"); an = document.getElementById("userAnswer"); L = document.getElementById("L").textContent; if (an == L) { feedBack.textContent = "good"; } else { feedBack.textContent = "bad"; } }
 <input id="userAnswer" type=text> <input id="userAnswer" type=text> <input id="userAnswer" type=text> <button onclick="F1()">check</button> <label id="L"> </label> <p id="feedBack"> </p>

You could try to loop over the input elements and then validate each element, in the loop save the value of the input in a set/array for each input so with this we would have a cache to check the input field values.

 function validate() { let numberEntered = new Set(); let allowedValues = [1, 2, 3]; let inputStatus = false; let feedBack = document.getElementById("feedBack"); let inputEle = document.querySelectorAll(".number-field"); for (let input of inputEle) { let value = parseInt(input.value); if (allowedValues.includes(value) && !numberEntered.has(value)) { numberEntered.add(value) } else { inputStatus = true; break; } } if (inputStatus) { feedBack.textContent = "Bad"; } else { feedBack.textContent = "good"; } }
 <input id="userAnswer1" class="number-field" type=text> <input id="userAnswer2" class="number-field" type=text> <input id="userAnswer3" class="number-field" type=text> <button onclick="validate()">check</button> <label id="L"> </label> <p id="feedBack"> </p>

It's worth mentioning (especially for the more novice JavaScripters reading this) that, as with most programming problems, there are lots of ways to correctly satisfy the requirements from the original question.

I know this isn't Code Review.SE , but you might benefit from some feedback on the example you provided, if you're interested:

  1. The variables a , b , and c are never used in any particularly useful way, and detract from the human readability of your code. You should probably remove their declarations entirely.
  2. You set the variable L three times consecutively. This doesn't do very much at all, considering also L is overridden once F1() is executed. You should probably remove these unnecessary assignments entirely.
  3. The HTML specification is clear that ID values should be unique across the entire document space; anything else is invalid and can lead to headaches and undocumented behavior down the line, especially when JavaScript comes into play. In the simplified example, there really isn't any need to assign them ID s at all (see solution).
  4. Relatively minor, but inline event handling (ie, using the onclick attribute) is generally regarded as an outdated concept. Instead, use the addEventListener() paradigm to make your code easier to interpret and debug.
  5. The function name F1() isn't particularly descriptive to what the function actually does when called. A future developer maintaining your code would have a less difficult time discerning what this method does if it was named something more descriptive, like validateForm() , or even just validate() .

To satisfy your requirements, you might look to write something more like what I've got below. In a nutshell, when the validate() function is run, the following actions are taken:

  1. Instantiates validNumbers , an array of the valid inputs to be validated against he fields.
  2. Instantiates inputFields which evaluates to a NodeList iterable which can be looped.
  3. Instantiates feedbackElement , a reference to your <p> node in the DOM.
  4. Loops all the inputFields , and checks if the value of the current field is in the validNumbers array.
  5. If the validation is successful, the code removes the valid value from the validNumbers array (as it's already been used and can't be used again) and proceed to validate the next field.
  6. If the validation is unsuccessful, the code automatically sets the text of your feedback element to "bad" and breaks out of the validation loop.
  7. Once all three input fields have been validated, the code checks to see if there are any remaining elements of validNumbers left. If there are, not all elements were used and the feedback is once again set to "bad" . Otherwise, the validation checks out and the feedback element's contents are set to "good" .

 function validate() { var validNumbers = [1, 2, 3]; var inputFields = document.querySelectorAll("input[type='text']"); var feedbackElement = document.querySelector("p#feedBack"); for (field of inputFields) { var fieldValue = parseInt(field.value); if (validNumbers.includes(fieldValue)) { // valid number & not encountered yet validNumbers.splice(validNumbers.indexOf(fieldValue), 1); } else { // invalid number or already used feedbackElement.innerText = "bad"; break; // break out of `for` loop, as there's already no possible way for the provided numbers to be "good" } } if (validNumbers.length === 0) { // all numbers were used feedbackElement.innerText = "good"; } else { // not all numbers were used feedbackElement.innerText = "bad"; } } document.querySelector("button").addEventListener('click', function() { validate(); });
 <input type=text> <input type=text> <input type=text> <button>check</button> <p id="feedBack"> </p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM