How to display the text in the datalist and not its value?

Asked

Viewed 1,278 times

2

I made a built-in autocomplete in a field input without much difficulty, as shown below:

<label>Professor</label>
<input type="text" list="list-professor" name="professor_id">
<datalist id="list-professor">
   <select>
      <option value="1">Roberto</option>
      <option value="2">Rosana</option>
      <option value="3">Romualdo</option>
   </select>
</datalist>

The datalist always returns the value contained in the attribute value.

I would like to complete the input guy text with the Name of the Person, but did not want to lose the ID when sending the form.

I thought I’d try to assign the value of ID's in a field of the kind hidden, but I don’t know how to assign the value when there is selection in datalist.

  • I added an answer just below, so I understand you wanted to send the idand select the name of Professor

  • 1

    Erick I made a few edits that I think is pertinent, in case you do not inform me that I return as before, welcome to Stackoverflow, I recommend reading on tour to understand a little more about how things work around here.

  • Thank you so much for your contribution! I made the implementation according to your guidance and solved my problem.

1 answer

4


I understand you want to send the id and the input displays the teacher’s name.

I made a little change in yours HTML, in value add the names of Teachers, and in data-value put the id.

$(document).ready(function() {
    $('button').click(function() {
        var value = $('input').val();
        console.log($('#list-professor [value="' + value + '"]').data('value'));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Professor</label>
<input type="text" list="list-professor" name="professor_id">
<datalist id="list-professor">
   <select>
      <option data-value="1" value="Roberto"></option>
      <option data-value="2" value="Rosana"></option>
      <option data-value="3" value="Romualdo"></option>
   </select>
</datalist>
<button>Enviar</button>

I recommend reading:

  • 1

    Marconi, the solution you presented solved my problem perfectly. I made a small change in your code where I changed the event to 'focusout' on its own 'input' guy 'text' amending the 'value' of a 'input' guy 'Hidden' with the 'data-value'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.