0

I want to get the user selection for a quiz.

I am doing this by using const choiceA = document.getElementById("A").value;

There are four choices and instead of creating 4 different const could I do something like. const choice = document.getElementById("A", "B"....).value

Or is there any other way to do this short hand?

Any links to good information about gathering user input would be much appreciated too :)

<html>
        <form id="formEl">
            <h2 id="question"></h2>
            <button id="A" type="button" class="userSelection"></button>
            <button id="B" type="button" class="userSelection"></button>
            <button id="C" type="button" class="userSelection"></button>
            <button id="D" type="button" class="userSelection"></button>
            <button id="previous" type="button" class="userSelection">Previous</button>
            <button id="next" type="button" class="userSelection">Next</button>
            <button id="submit">Submit</button>

        </form>

<js>
class Question {
    constructor(question, ansA, ansB, ansC, ansD, answer) {
        this.question = question;
        this.ansA = ansA;
        this.ansB = ansB;
        this.ansC = ansC;
        this.ansD = ansD;
        this.answer = answer;
    };

    checkAns(ansSelected, answer) {
        if (ansSelected === answer) {
            console.log('Well Done')
        };
    };
};

//Questions
var questionOne = new Question('Where is Creete?', 'Barcalona', 'Greece', 'Dubi', 'Ireland', 'Greece');
var questionTwo = new Question('How many times have Liverppool won the Champions Legue?', '1', '4', '6', '5', '6');
var questionThree = new Question('Where was the first Godfather in the mafia from?', 'Milan', 'Gunoa', 'Rome', 'Napoli', 'Napoli');

//Index of the array with the questions array 
var i = 0;
const arrayQuestion = [questionOne, questionTwo, questionThree];

//Selecting the value of the user once clicked
const choiceA = document.getElementById("A").value;
const choiceB = document.getElementById("B").value;
const choiceC = document.getElementById("C").value;
const choiceD = document.getElementById("D").value;
Liam
  • 568
  • 2
  • 15
  • 2
    You shouldn't be using `buttons` here, you should use radio buttons and then you won't have to test to see which button was selected. [See this for the proper way to handle multiple choice user input.](https://stackoverflow.com/questions/49243460/how-to-check-if-a-input-type-button-is-checked/49243766#49243766) – Scott Marcus Aug 29 '19 at 16:47
  • @Scott Marcus, Thanks for the read : ) – Liam Aug 29 '19 at 17:06
  • few things about markup.. 1) you *should* wrap your contents in a `` tag as well as the `` one. 2) I don't think I've ever seen `` before.. it may be valid but the more common practice is ` – treyBake Aug 29 '19 at 17:56

2 Answers2

0

I recommend you to dont use buttonbecause they only execute scripts or onclick,functions,they cant save a variable or a value, it will be much easier to use select so you can read the selectedIndex example:

<select name="Class" id="Class">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
//This is for you to see the selected value
  <input type="text" name="valorsel" id="valorsel" class="form-control" placeholder="Selected Index Value">

This will be the script

<script>
function myFunction()
{
//Getting the value
  var selObj = document.getElementById("Class");
  var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
 document.getElementById("valorsel").value = selValue;
}
</script>
  • You don't actually need to access the `selectedIndex.value`. You can just get the `.value` of the `select` element itself. The `value` of whatever `option` has been chosen will become the `value` of the `select` itself. – Scott Marcus Aug 29 '19 at 18:11
  • That would be a more simple way of doing it – Ulises Ontiveros Aug 29 '19 at 18:35
0

This may be a bit old school. But :) If it has to be a button then you can not just evaluate the form. They will give always their value as you can see in below running code. If we want to abuse buttons we have to be a bit tricky. I use a input field to get and edit the values. Can be hidden for sure afterwards. The native html soloution would be radio buttons if only one answer would be ok or checkboxes if some answers could be ok. the serialize function would then give you all values in a good style. Some suggested option input field which are in my opinion unhandy. But taste is different. in my "getanswer" routine you can easy add some style changes - make the button red if he is active or whatever. I also sort the result to make it easy to compare with the right answer. The html part could be also written automatically in your document.

function changeform(formid,html) {
document.getElementById(formid).nextElementSibling.innerHTML=html; 

}


<!DOCTYPE html>
<html>
<body>
    <form id="formEl" name="formEl" onsubmit="done(this)">
    <div>
        <button id="A" type="button" class="userSelection" NAME="A" 
 VALUE="A" 
 onclick="edanswer('A')">A</button>
        <button id="B" type="button" class="userSelection" NAME="B" 
 VALUE="B" 
 onclick="edanswer('B')">B</button>
        <button id="C" type="button" class="userSelection" NAME="C" 
 VALUE="C" 
 onclick="edanswer('C')">C</button>
        <button id="D" type="button" class="userSelection" NAME="D" 
   VALUE="D" 
    onclick="edanswer('D')">D</button>
    </div>
        <input type="submit" value="gotcha">
        <input id="result" name="result">
    </FORM>
    <SCRIPT>
        function edanswer(answer) {
            result = formEl.elements["result"].value
            if (result.indexOf(answer) < 0) {
                result = result + answer;
            } else {
                result = result.replace(answer, "");
            }
            //sort result to ease further processing / evaluation
            arr = result.split('');
            arr.sort();
            result = arr.join('');
            formEl.elements["result"].value = result;
        }
        function done(x) {
            alert(x.result.value);
            alert(serialize(x)); 
            // just to clarify the form button issue
            // the preferred input type would be a checkbox 
            // on submit they give sound values without hussle

        }


        //https://code.google.com/archive/p/form-serialize/downloads
        function serialize(form) {
            if (!form || form.nodeName !== "FORM") {
                return;
            }
            var i, j, q = [];
            for (i = form.elements.length - 1; i >= 0; i = i - 1) {
                if (form.elements[i].name === "") {
                    continue;
                }
                switch (form.elements[i].nodeName) {
                case 'INPUT':
                    switch (form.elements[i].type) {
                    case 'text':
                    case 'hidden':
                    case 'password':
                    case 'button':
                    case 'reset':
                    case 'submit':
                        q.push(form.elements[i].name + "=" + 
 encodeURIComponent(form.elements[i].value));
                        break;
                    case 'checkbox':
                    case 'radio':
                        if (form.elements[i].checked) {
                            q.push(form.elements[i].name + "=" + 
  encodeURIComponent(form.elements[i].value));
                        }
                        break;
                    case 'file':
                        break;
                    }
                    break;
                case 'TEXTAREA':
                    q.push(form.elements[i].name + "=" + 
 encodeURIComponent(form.elements[i].value));
                    break;
                case 'SELECT':
                    switch (form.elements[i].type) {
                    case 'select-one':
                        q.push(form.elements[i].name + "=" + 
  encodeURIComponent(form.elements[i].value));
                        break;
                    case 'select-multiple':
                        for (j = form.elements[i].options.length - 1; j >= 0; j = j - 
1) {
                            if (form.elements[i].options[j].selected) {
                                q.push(form.elements[i].name + "=" + 
 encodeURIComponent(form.elements[i].options[j].value));
                            }
                        }
                        break;
                    }
                    break;
                case 'BUTTON':
                    switch (form.elements[i].type) {
                    case 'reset':
                    case 'submit':
                    case 'button':
                        q.push(form.elements[i].name + "=" + 
 encodeURIComponent(form.elements[i].value));
                        break;
                    }
                    break;
                }
            }
            return q.join("&");
        }
    </SCRIPT>
 </body>
</html>
Thomas Ludewig
  • 696
  • 9
  • 17