简体   繁体   中英

Select datalist value on input change and populate the form using jQuery javascript

I am trying to do autocomplete, when input is changed and an option is selected from the datalist, then I want the form and text field to be populated with selected value/text from the datalist. I tried many options from similar questions here on stackexchange, but not able to make it work.

Help!

 $(document).ready(function() { $('#UserCity').on('input', function() { var str = ""; console.log($(this).val()); $("#UserCitySelect").on('select', function() { str += $(this).text() + " "; }); str = $("#UserCitySelect option:selected").text() console.log(str); document.getElementById("selected").text = str; document.getElementById("selecteddiv").innerHTML = str; console.log($(this).val()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="UserCity" id="UserCity" label="User City" max_length="25" list="UserCitySelect" required=""> <p id="selected"><p> <div id="selecteddiv"><div> <datalist id="UserCitySelect"> <option value="Los Angeles">Los Angeles</option> <option value="New York">New York</option> <option value="Chicago">Chicago</option> </datalist>

:selected does not work on datalist options, as one datalist can provide suggestions for multiple inputs. If two different inputs contain two different suggestions from the list, which would be the selected one?

you can check the value of the input on change with event of input text and assign the value in div with the id.

 $(document).ready(function() { $("input[name='UserCity']").on('input', function(e){ var selectedVal = $(this).val(); document.getElementById("selected").innerHTML = selectedVal; document.getElementById("selecteddiv").innerHTML = selectedVal; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="UserCity" id="UserCity" label="User City" max_length="25" list="UserCitySelect" required=""> <datalist id="UserCitySelect"> <option value="Los Angeles">Los Angeles</option> <option value="New York">New York</option> <option value="Chicago">Chicago</option> </datalist> <p id="selected"></p> <div id="selecteddiv"><div>

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