HTML5 datalist value vs. inner-text

前端 未结 2 446
陌清茗
陌清茗 2021-01-12 03:18

I have an issue that is manifesting between Chrome and Firefox\'s handling of the HTML5 datalist element.

I may be abusing it, which Firefox is handling the way I ex

相关标签:
2条回答
  • 2021-01-12 03:40

    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();  
    }
    
    0 讨论(0)
  • 2021-01-12 04:00

    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.

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