3 Replies - 200 Views - Last Post: 05 May 2019 - 03:55 AM

#1 WDebowsky   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-May 19

How to check if input is correct or not

Posted 04 May 2019 - 10:51 AM

Hey I want to make a website where you can write an input and check if it's correct or not. I have tried many things but everytime it changes color to red which is wrong, even if I write a good answer.


<div id="questions">
  <p>1. The Sun
    <input type="text">
    <button>Check!</button>
  </p>
  <p>2. B ==
    <input type="text">
    <button>Check!</button>
  </p>
</div>



const correct = [3, 2]; // 

Array.from(document.querySelectorAll("#questions p")).forEach((p, i) => {
  p.querySelector('button').addEventListener("click", function() {
    const select = p.querySelector('select');
    select.style.color = select.selectedIndex + 1 === correct[i] ? "green" : "red";
  });
});



What do I do wrong?

I'm sorry. this is correct javascript code

const correct = ["shines", B]; // 

Array.from(document.querySelectorAll("#questions p")).forEach((p, i) => {
  p.querySelector('button').addEventListener("click", function() {
    const select = p.querySelector('input[type="text"]');
    select.style.color = select.selectedIndex + 1 === correct[i] ? "green" : "red";
  });
});




Is This A Good Question/Topic? 0
  • +

Replies To: How to check if input is correct or not

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5418
  • View blog
  • Posts: 14,331
  • Joined: 18-April 07

Re: How to check if input is correct or not

Posted 04 May 2019 - 06:47 PM

select.selectedIndex + 1? Not sure what you are wanting to do there, but if you simply change it to select.value you will have solved world peace and their will be no more war in the world. :D

Spoiler

This post has been edited by Martyr2: 04 May 2019 - 06:49 PM

Was This Post Helpful? 0
  • +
  • -

#3 WDebowsky   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-May 19

Re: How to check if input is correct or not

Posted 04 May 2019 - 11:27 PM

View PostMartyr2, on 04 May 2019 - 06:47 PM, said:

select.selectedIndex + 1? Not sure what you are wanting to do there, but if you simply change it to select.value you will have solved world peace and their will be no more war in the world. :D/>


I changed it and it only works for the first sentence. Second isn't working correct and always returns red color even if the answer is correct. It looks like the correct answer for second is also "shines" and its checking 3
Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6798
  • View blog
  • Posts: 28,102
  • Joined: 12-December 12

Re: How to check if input is correct or not

Posted 05 May 2019 - 03:55 AM

Post your revised code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1