简体   繁体   中英

Change a class with a selector using javascript

I'm new to web programming, and I have been trying to do a true/false test, and when the answers are submitted, the answers change colors depending if it's correct or not.

At first, I used labels for each input:

<h3>1. Father Christmas and Santa Claus are the same man</h3>
     <input type="radio" id="1bon" name="q1" value="Non" >  
          <label for="1bon" > True </label> <!-- label is for css -->
     <input type="radio" id="1non" name="q1" value="Bon">
          <label for="1non"  > False </label><br/>

And in the css, I used " input[value=Bon] + label" or "input[value=Non] +label" with a "background color : blue ", and in a JS, I used label[i].style.background to change the color. It's does change the color, but only of the radio button, and when not checked, which is exactly what I'm trying to do. It comes from the fact I don't know how to select the label of a precise input[x=y]:selector.

So I rewrote the whole thing without any labels

<h3>1. Father Christmas and Santa Claus are the same man </h3>       
     <input type="radio" class="input" id="1bon" name="q1" value="Non">  True 
     <input type="radio" class="input" id="1non" name="q1" value="Bon"> False 

With new css:

.input {
background-color: #fff;
display:inline-block;
width:5%;
padding:10px;
border:1px solid #ddd;
margin-bottom:10px;
cursor:pointer; /* new selectoon type */
}
.input:checked{
background-color: #4876ff;
}

So, when just checked, it is blue, but when the answers are submitted, depending of the value of the input, it change the color of the class:checked.

It there any way do modify the style of a class with a selector in javascript ? Also, if the user decides to change his answer for a question, the checked have to go back to being color neutral.

Thank you for your help.

You can use this function to change class of element as you explained earlier. But changing color of checkbox is not possible without using third party plugin or customized elements. Please check this link

function Test2($this){
var radios = document.getElementsByName('q1');
for(i=0; i< radios.length; i++){
    var element = radios[i];
    element.classList.remove("correctAnswer");
    element.classList.remove("wrongAnswer");
}
if($this.value === "Non"){//Assume "Non" is correct answer
$this.classList.add("correctAnswer");
}else{
$this.classList.add("wrongAnswer");
}
}

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