Home > database >  change background color of selected button with JavaScript/jQuery
change background color of selected button with JavaScript/jQuery

Time:01-14

I am creating a quiz and want to change color of button selected by user.

var start = true;

if (start) {
    begin(0);
}

function begin(id) {

    // placing questions
    const question = document.getElementById("question");
    question.innerText = Questions[id].q;

    // placing options
    document.getElementById('op1').innerText = Questions[id].a[0].text;
    document.getElementById('op2').innerText = Questions[id].a[1].text;
    document.getElementById('op3').innerText = Questions[id].a[2].text;
    document.getElementById('op4').innerText = Questions[id].a[3].text;

    $(".btn").click(function () {

        var selected = $(this).attr("id");
        selected.style.backgroundColor="red";
    }
    );

}

Questions contains questions with options in json format. The color of selected button is not changing, I am really new to JavaScript, someone help please.

CodePudding user response:

Just use jQuery object $(this), $(this).css('background-color','red'); to change button color when click.

Or get id via document.getElementById("Your-button-id").

Note: Please avoid mismatch jQuer and JavaScript

Examples:

$(".btn").click(function() {
  $(this).css('background-color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="quiz" class='btn' id='btn' />

Or:

$(".btn").click(function() {
  let selected = document.getElementById("btn");
  selected.style.backgroundColor = "red";
});
<!-- begin snippet: js hide: false console: true babel: false -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="quiz" class='btn' id='btn' />

  • Related