Getting the value and text from a datalist in jquery

后端 未结 2 370
予麋鹿
予麋鹿 2021-01-28 17:41

I am trying to get the value in the #place input and keep it in that input but have the fax number go into the #fax input? Is it possible to get both values and drop them into

相关标签:
2条回答
  • 2021-01-28 18:16

    There are two things you need to do to achieve this effect given the starting code you gave us. First, you need to capture any change to your input element by adding an event listener.

    Second, using javascript you just need to select the correct option element from all of the ones present, and extract the fax number, which is the tags innerHTML.

    <input type="text" id="place" list="places">
    <datalist id="places">
        <option value="WVC">503-882-1212</option>
        <option value="HAM">612-883-1414</option>
        <option value="WON">317-445-8585</option>
    </datalist>
    <br>
    <input type="text" id="fax">
    <script>
        document.querySelector('input').addEventListener('input', function () {
            var val = document.querySelector('input').value;
            faxNum = document.querySelectorAll('option[value="' + val + '"]')[0].innerHTML;
            document.querySelector('#fax').value = faxNum;
        });
    </script>
    
    0 讨论(0)
  • 2021-01-28 18:20

    try using jquery attr value

         $(document).on('change', '#place', function () {
             $("#fax").val($("#places option[value='" + $("#place").val() + "']").attr("label"));
          });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="place" list="places">
        <datalist id="places">
            <option value="WVC" label="503-882-1212"></option>
            <option value="HAM" label="612-883-1414"></option>
            <option value="WON" label="317-445-8585"></option>
        </datalist>
        <br>
        <input type="text" id="fax">

    0 讨论(0)
提交回复
热议问题