Home > OS >  Using Input Values as Query String on Rest API
Using Input Values as Query String on Rest API

Time:10-01

How do I use HTML input(type: color) as a query string on API

here's my code:

const colorPicker = document.getElementById("color_picker");
const color = colorPicker.value;
const url = `https://www.thecolorapi.com/id?hsl=${color}`

  fetch(url)
    .then(res => res.json())
    .then(data => console.log(data))
<input type="color" id="color_picker" />

I tried using the input value as the query string(ID) to generate the color with the input value instead of hand_coding it in Javascript but it's not working. Please can you help specify a better way of doing this.

CodePudding user response:

You're generating your URL by mashing strings together without accounting for the presence of special characters.

A colour code starts with a # which is also the character which signals the end of a query string and the start of a fragment id in a URL.

Use an API to build your URL instead of string mashing.

const colorPicker = document.getElementById("color_picker");
const color = colorPicker.value;
const url = new URL("https://www.thecolorapi.com/id");
url.searchParams.append('hsl', color);
fetch(url).etc.etc…

(This also needs to go in a function that you call after a colour has been picked, but I'm assuming you just omitted that part from the question.)

CodePudding user response:

Are you using vanilla Javascript or some framework?

Where are you setting colorPicker?

If you're using vanilla JS then maybe it should be

const color = document.getElementById("color").value; //and I think that returns a hex color

const url = `https://www.thecolorapi.com/id?hex=${color}`
  • Related