Search code examples
javascriptjquerycsshtmlhtml-datalist

datalist get selected value and custom attribute (without events)


I have a datalist with options and a custom attribute.

<input list="selectedItems" class="selectedItemsList"></input>
                                <datalist id="selectedItems">
                                    <option value="test11" oldvalue="f1"></option>
                                    <option value="test12" oldvalue="f2"></option>
                                </datalist>

It is displayed on a popup. When a popup closes the value and custom attribute value must be used in a function...

I tried:

alert($("#selectedItems option:selected").val());

alert($("#selectedItems option:selected").attr("oldvalue"));

$('.selectedItemsList option').each(function() {
    if($(this).is(':selected')){
     alert($(this).val());
   }
});

for (var i=0; i<document.getElementById('selectedItemsList').options.length; i++)
                { 
                    if (document.getElementById('selectedItemsList').options[i].value ==  document.getElementsByName("selectedItems")[0].value) 
                    { 
                      alert(document.getElementById('selectedItemsList').options[i].value);
                      break;
                    }                                                
               }

Nothing works.


I can get the values using on-event but that is not an option for me.

$('.selectedItemsList').on('input', function() { ...  
alert($(this).val());

Solution

  • $(function(){$("input[name=selectedItems]").on('input', function(){// selects which array raw is edited
                for (var i=0; i<dList.length; i++) if(dList[i].ItemName===$(this).val()) { num = i;
                $(".selectedItems option[value="+dList[num].ItemName+"]").val($(this).val());
                dList[num].ItemName=$(this).val();
            });
        });
    

    So, I use datalist oninput event to get the selected value. Then, I edit a raw of an array of values that represents the datalist values.

    var dList=[];num=0;
    dList.push({ItemName: $(this).attr('value'), ViV: vs[0], NU: vs[1], ItemKey: $(this).attr('key')});