Jayesh Vyas
Jayesh Vyas

Reputation: 31

change color onclick event in button

I am facing a problem in my code. I want to change the color of the button when it is clicked. you can check my code which is given below.

<html>
    <head>
    </head>
    <body onload="func();">
        <br><br><div id="header"><h1 align="center">Online Aptitude-2k17</h1></div>
        <table align="center" width="100%">
            <tr id="t1">
                <td></td>
            </tr>
        </table>

        <script>
            function func() {
                for(var i=1;i<=30;i++) {
                    var x=document.getElementById("t1").innerHTML;
                    var p="<td><input type='button' value='"+i+"' onclick ='myFunction("+i+");'/></td>";
                    document.getElementById("t1").innerHTML=x+p;
                }
            }

            function myFunction(a,elem) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4 && this.status == 200) { 
                        document.getElementById("ques").innerHTML = this.responseText;

                    }
                };
                xhttp.open("GET", "retrieveQuestion.php?question=" +a, true);
                xhttp.send();
            }
        </script>

        <div id="ques" style="text-align:center; padding:20px"></div>
        <table align="center" cellspacing="20px">
            <tr><td align="center"><input type="text" name="answer" /></td></tr>
            <tr><td align="center"><input type="button" value="Submit" /></td></tr>
        </table>
      </body>
</html>

Button which are contains 30 col in a single row what i want is when a user clicks on it it must be changed it's color when it is clicked.

Can anyone help me for this problem.

Upvotes: 0

Views: 1211

Answers (2)

Byndd IT
Byndd IT

Reputation: 296

make all color in array

$("button").click(function(){
    var color = clicked ? 'red' : 'blue';
    $(this).css('background-color', color);
    clicked = !clicked;
});

Upvotes: 2

xxfast
xxfast

Reputation: 737

Here's some example you can try implementing in your own code

function changeColor(e){
 e.style.backgroundColor = "red";
}

function populate() {
   for(var i=1;i<=30;i++) {
      var x=document.getElementById("holder").innerHTML;
      var p="<input style='background-color: #4CAF50' type='button' value='"+i+"'onclick='changeColor(this)'/>";
      document.getElementById("holder").innerHTML+=p;
   }
}

populate() ;
<div class="container">
<table id="holder"></table>
</div>

Upvotes: 0

Related Questions