HTML5 datalist value vs. inner-text

我只是一个虾纸丫 提交于 2019-12-01 03:50:51

I'm trying to do something similar. I think the issue is the datalist isn't spec'ed to work like a dropdown option list. One work around is that you generate both an <%=OptionsList%> and then an array <%=OptionListValues %>...so once you get the text value in your input, you can use javascript to look for it's key in the OptionListValues and send the key instead of the description back to the server. Pain in the rear and adds an extra data load on the client side, though I guess you could do this server side as well (send the text in the input and then lookup the text and get the key on the server side).

Too bad Chrome doesn't work like FF on this, maybe in the future the browsers will work like Mozilla on this.

Or you can do something like this. Say you have the following input/datalist

<input id="datalisttestinput" list="stuff" ></input>
        <datalist id="stuff">
            <option id="3" value="Collin" >
            <option id="5" value="Carl">
            <option id="1" value="Amy" >
            <option id="2" value="Kristal">
        </datalist>

You can use jQuery (or plain javascript) to dig out the id value...here is my example, I'm sure this could be optimized a bit.

 function GetValue() {
            var x = $('#datalisttestinput').val();
            var z = $('#stuff');
            var val = $(z).find('option[value="' + x + '"]');
            var endval = val.attr('id');
            alert(endval);
        }

That should get you going.

Slightly modifying infocyde's answer to use a hidden field to contain the value which ultimately gets sent to the server.

$('#inputStates').change(function(){
    var c =  $('#inputStates').val();
    $('#inputStates').val(getTextValue());
    $('#statesHidden').val(c);
});

function getTextValue(){
  var val =  $('#inputStates').val();
  var states = $('#states');
  var endVal = $(states).find('option[value="' + val + '"]'); 
  //depending on your logic, if endVal is empty it means the value wasn't found in the datalist, you can take some action here
  return endVal.text();  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!