I am developing a probability calculator and I can't manage to get the 'value' out of the datalist. I'm very new to javascript so maybe it's very easy but I don't know how to do it yet.
I tried using object.value but it does not seem to work. Do you have any ideas?
Here's my javascript code:
//test
let test = document.getElementById("name");
test.addEventListener("input", () => console.log(test.value));
// variables
let q = document.getElementById("submit");
let q1 = document.getElementById("q1");
q.addEventListener('click', () => console.log("works"));
q.addEventListener('click', probability_calculation()));
function probability_calculation() {
if (q1.value === 'Rap') {
alert("works");
console.log("works well");
} else if (q1.value === 'Alter') {
console.log('33%');
} else if (q1.value === 'Pop') {
console.log('97%');
}
}
<h1 class="header">Probability Calculator</h1>
<div>
<input type="text" placeholder="Enter your name" id="name">
<input list="q1" placeholder="What is your favourite type of music?">
</div>
<panel class="center-q">
<datalist id="q1">
<option>Rap</option>
<option>Alter</option>
<option>Pop</option>
</datalist>
</panel>
<input type="submit" id="submit">
In this line
q.addEventListener('click', probability_calculation()));
probability_calculation
function but just pass it itself as a callback handler to event listenerThe correct version is
q.addEventListener('click', probability_calculation);
Also, you have two tags with the same identifier q1
.
I simplified your datalist
stuff to simple select
in order to show the working version.
See jsfiddle