Home > Enterprise >  I want to change background colour when I click input
I want to change background colour when I click input

Time:11-06

 <input type="submit" value="Login" onclick="myFunction">

  <!-- Project -->
  <script>
    
    function myFunction(){
      document.getElementById("input[tpye="submit"]").style.backgroundColor="blue";
    }
    
  </script>

CodePudding user response:

getElementById gets the element with that id. You're probably looking for querySelector instead, which will select the element that matches that selector:

function myFunction(){ 
    document.querySelector("input[type='submit']").style.backgroundColor="blue";
 }

CodePudding user response:

You have done three mistakes in your code snippet

  1. You have not given () to the function call
  2. You have written incorrect spelling in the querySelector of "type" word
  3. You are calling the getElementById() function but you have not given id to the input box

<input type="submit" value="Login" onclick="myFunction()">

<!-- Project -->
<script>
  
  function myFunction(){
    document.querySelector("input[type='submit']").style.backgroundColor="blue";
  }
  
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

In the javascript function you are using 'getElementById' which means that it'll look for the DOM elements with the id you have provided, and the problem is you didn't provided any id.

You have to first give an id to the button

<button id="some_id">Click</button>

And then align your function in this way.

function myFunction(){ document.getElementById("some_id").style.backgroundColor="blue"; }

CodePudding user response:

this is my solution to your problem. In your case you have some type of input, you need first to add an event listener to the input, which will execute some function on a specific event. In our case, we will execute the change color function.

This is a quick solution to your problem.

let button = document.getElementById('changecolor');

let input = document.getElementById('basic-input');


function changeBackground(){
    // Change the background of the page
    document.body.style.background = 'red';
  
  // Change background of the button
  button.style.background = 'blue';
}

button.addEventListener('click' , changeBackground);

input.addEventListener('click' , changeBackground);
<button id="changecolor">Change background</button>

<input type="text" placeholder="basic input" id="basic-input">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related