1

When I select a (array) value. I want to call a function that displays the selected value.

How can I do this?

    <input name="car" list="anrede"  />
    <datalist id="anrede"></datalist>

    <script>
      var mycars = ['Herr','Frau'];
      var list = document.getElementById('anrede');

      mycars.forEach(function(item){
        var option = document.createElement('option');
        option.value = item;
        list.appendChild(option);

      });
    </script>

2 Answers 2

2

You can add the change event to your input.

var mycars = ['Herr','Frau'];
var list = document.getElementById('anrede');

mycars.forEach(function(item){
  var option = document.createElement('option');
  option.value = item;
  list.appendChild(option);
});
document.querySelector('input[name="car"]').addEventListener('change', function(e) {
   if (mycars.indexOf(e.target.value) > -1) {
        console.log('value in array');
   }
  console.log(this.value);
});
<input name="car" list="anrede"  />
<datalist id="anrede"></datalist>

Sign up to request clarification or add additional context in comments.

Comments

1

The selected value is shown in the input tag when you choose it. If you want a function which displays it in a different way, do this: (note: I don't know the way you want to display the value so in this example, I will show you how to display it in a <p> tag. Then you will be able to do it however you want)

The HTML: add an id and onchange attributes to the input:

<input name="car" list="anrede" id="car" onchange="function1();">
<datalist id="anrede"></datalist>
<p id="example"></p>

The onchange attribute calls the function function1 when you choose a value.

note: the end of the input tag is just > and not />.

Now, the javascript: add the function function1 to display the selected value

function function1()
{
  var val = document.getElementById("car").value;
  document.getElementById("example").innerHTML = val;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.