skip to Main Content

I’m new to JS however i have some Python background.I’m developing a web-app using flask however in some of my HTML templates i have to use JS <script>. So i have a dropdown list of options, which is a datalist. Is there a way to say "if input_value in datalist then"?

I think it should look sth like

if (input_value in datalist){
    do some stuff
}

Idk how to say in though.

i have tried searching for an answer using scripts from ES6 and ES5 however they dont really work for me.

I’ve tried after finding an answer on the same issue using .indexOf saying that if its -1 then it doesn’t exist in the list. However i get this error: datalist.indexOf is not a function.

Here is part of the js code:

var selectedClientInput = document.getElementById("selected-client");
var selectedClient = selectedClientInput.value;

var datalist = document.getElementById("clients");
var options = datalist.getElementsByTagName("option");

if (options.indexOf(selectedClientInput) == -1){
    throw new Error("Please select a client from the dropdown list.");
}

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to @Pointy @Barmar and @Mike 'Pomax' Kamermans i managed to get to the solution. As they pointed i wasnt using an array but a nodelist so i just had to convert it into an array and use its functions. Here is the completed code:

    var selectedClientInput = document.getElementById("selected-client");
    var selectedClient = selectedClientInput.value;
    
    var datalist = document.getElementById("clients");
    var options = datalist.getElementsByTagName("option");
    
    if (Array.from(options).some(option => option.value === selectedClient)){
    
        do something ; 
    }
    else {
    
        throw new Error("Please select a client from the dropdown list.");
    
    }

    As you can see the options NodeList has been converted to an array using:

    Array.from(options)


  2. Without seeing the HTML, here is another option. You can use querySelector of datalist to see if an option exists with the value from selectedClient.

    const selectedClientInput = document.getElementById("selected-client");
    let selectedClient = selectedClientInput.value;
    
    const datalist = document.getElementById("clients");
    let options = datalist.querySelector("option[value='" + selectedClient + "']");
    
    if(!options){
      console.log("Please select a client from the dropdown list.")
    }
    else{
      console.log("Found!");
    }
    <input type="text" id="selected-client" value="client1">
    <input list="clients" id="clientList" />
    <datalist id="clients">
      <option value="client1"></option>
      <option value="client12"></option>
      <option value="client13"></option>
      <option value="client14"></option>
      <option value="client15"></option>
    </datalist>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search