简体   繁体   中英

datalist how to tell if selected input in dropdown

 <label>Choose a browser from this list:
    <input id = "a" list="browsers" name="myBrowser" 
      style="width: 400px;" onchange="castvote()"  /></label>
  <datalist id="browsers">
    <option value="Chrome">
    <option value="Firefox">
    <option value="Internet Explorer">
    <option value="Opera">
    <option value="Safari">
    <option value="Microsoft Edge">
  </datalist>

function castvote() {
    var datalist = document.getElementById('a');
   // var datalist = document.getElementById("a").children; // this did not work as well
    console.log("Chrome" in datalist);
    }

when i select Chrome or any other options and check to see if it is one of the options i wanted (one of the drop down options) the console is returning false. How do I make it return true (detect that one of the options I selected is indeed the dropdown options)? If possible no Jquery please

 function castvote() { var datalist = document.getElementById('a'); // var datalist = document.getElementById("a").children; // this did not work as well // console.log("Chrome" in datalist); var browserChildren = document.getElementById('browsers').children var flag = false for(let i = 0; i < browserChildren.length; i++){ flag = browserChildren[i].value === datalist.value || flag } console.log(flag) }
 <label>Choose a browser from this list: <input id = "a" list="browsers" name="myBrowser" style="width: 400px;" onchange="castvote()" /></label> <datalist id="browsers"> <option value="Chrome"> <option value="Firefox"> <option value="Internet Explorer"> <option value="Opera"> <option value="Safari"> <option value="Microsoft Edge"> </datalist>

since you gave the options in the, you can't get something different to the options, and taking this in account, in the logic you described all the time the result will be true, if you want to get the selected value you can use the event object from the event listener. Here is an example of that.

As an extra note, is better if you add the listeners with "addEventListener" because you will get more control of the events, and add more than one event per element.

 const browsersDataList = document.getElementById("browser-choice"); browsersDataList.addEventListener("change", castvote); function castvote(event) { console.log(event.target.value) }
 #browser-choice { width: 400px; }
 <label for="browser-choice">Choose a browser from this list:</label> <input list="browsers" id="browser-choice" name="browser-choice" /> <datalist id="browsers"> <option value="Chrome"> <option value="Firefox"> <option value="Internet Explorer"> <option value="Opera"> <option value="Safari"> <option value="Microsoft Edge"> </datalist>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM