HTML / Javascript输入类型=“文本” - 如何显示与值不同的文本?

Actually i have a datalist:

<datalist id='modelsList'>
   <option value='1'>Dummy1</option>
   <option value='2'>Dummy2</option>
</datalist>

This is used in an input:

<input type='text' name='dummy' autocomplete='off' list='modelsList' value=''/>

If i start typing Dummy2 and then i click on the dropdown list result the textbox shows 2. I need to find a way to have 2 as value but Dummy2 as text.

I cannot use a drop-down list (select tag)

Here, my solution as per you want check it out... You can use input event for achieving such functionality,

HTML

<input type='text' id='dummy' list='modelsList'/>
<datalist id='modelsList'>
     <option value='1'>Dummy1</option>
     <option value='2'>Dummy2</option>
</datalist>

Jquery

$("#dummy").on('input', function () {
    var val = this.value;
    if($('#modelsList option').filter(function(){
        return this.value === val; 
    }).length) {
       var option = $('#modelsList').find('option[value="' + val + '"]');
       $(this).val(option.text());
    }
});

also check DEMO of the above code.

The format for a text input in HTML5 is as follows:

<input type="text" name="name" value="Value" placeholder="Placeholder Text">

As a user types in their content, the value changes.


You may be getting confused with textarea:

<textarea name="name">Value</textarea>

If you want to put a textarea tag, you have to know that the value attribute is invalid, but perhaps if you want to use it instead of input, and the format is similar as you put:

<textarea name="name">contentHere</textarea>