JSFiddle - React, Tailwind, and code Playground
HTML
<p>iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.</p>
Question ONE bla bla..? <br />
<input type="radio" name="CATEGORY_A" value="1"> Good<br>
<input type="radio" name="CATEGORY_A" value="2"> Average<br>
<input type="radio" name="CATEGORY_A" value="3"> Bad<br><br>
Question TWO bla bla..?<br>
<input type="radio" name="CATEGORY_B" value="1"> Good<br>
<input type="radio" name="CATEGORY_B" value="2"> Average<br>
<input type="radio" name="CATEGORY_B" value="3"> Bad<br><br>
Question Three bla bla..?<br>
<input type="radio" name="CATEGORY_C" value="1"> Good<br>
<input type="radio" name="CATEGORY_C" value="2"> Average<br>
<input type="radio" name="CATEGORY_C" value="3"> Bad<br>
JavaScript
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}