Home > Enterprise >  Is there a way to make user select a color/colour with only the option that you give them in JavaScr
Is there a way to make user select a color/colour with only the option that you give them in JavaScr

Time:11-17

Hey I was wondering if there is a way that you can make the user choose a colour/color with the options that you give them? I know there is a way to let user select a color/colour of thier choices but is there a way that you give the user only three options that change the background colour/color? for instance let say I want the user to only have the choice between black and blue how would I code this?

This is what I tried:

HTML Page:

<div >
    Pick a color <input onchange="colorSelected(this)" type="color">
  </div>

JavaScript Page:

function colorSelected (element) {
    document.body.style.background = element.value
}

But i want to be able to give the user limted options like only three colours (red, blue & yellow)

CodePudding user response:

let select = document.getElementById("select");
let text = document.getElementById("text");

select.onclick = function() {
  switch (select.value){
      case "red":
        text.style.color = "red";
        select.style.backgroundColor = "red";
      break;
      case "pink":
        text.style.color = "pink";
      select.style.backgroundColor = "pink";
      break;
      case "blue":
        text.style.color = "blue";
      select.style.backgroundColor = "blue";
      break;
  }
}
.color1{
  background-color:red;
}
.color2{
  background-color:pink;
}
.color3{
  background-color:blue;
}
<select id="select">
  <option hidden selected value="">Choose a color</option>
  <option value="red" ></option>
  <option value="pink" ></option>
  <option value="blue" ></option>
</select>
<p id="text">Some text</p>

Edited version

CodePudding user response:

Use a select with option for each choice.

Use your function in an eventListener that will pass the event object as an argument so you can get the value from the select (which is the event.target):

const mySelect = document.getElementById("my-select");
mySelect.addEventListener("change", colorSelected);

function colorSelected(event) {
  document.body.style.background = event.target.value
}
<select id="my-select">
  <option value="pick" hidden>Pick a color</option>
  <option value="red">Red</option>
  <option value="blue">Blue</option>
  <option value="yellow">Yellow</option>
</select>

  • Related