Reputation:
function selectFunction(letter){
document.getElementById("select").innerHTML = "Selection is : " + letter;
}
<html>
<head>
<title>Event on list of elements</title>
</head>
<body>
<div id="select">
<form>
<select onchange="selectFunction(this.value)">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</form>
</div>
</body>
</html>
I am new to java script, what I need to do here is that when one of the option is clicked result is on the same page, and that every time when I click another letter page shows a new result. I have no clue how to do this. I tried doing .innerHTML+=
but that shows a bunch of results, and I want a clean page.
Upvotes: 0
Views: 131
Reputation: 11622
You are replacing the HTML of your select
div, what you have to do is to create a child node with the text you calculated, and then append it to the HTML of select
div
Here is what you should do
function selectFunction(letter){
var node = document.createElement("div");
var textnode = document.createTextNode("Selection is : " + letter);
node.appendChild(textnode); //
document.getElementById("select").appendChild(node);
}
<html>
<head>
<title>Event on list of elements</title>
</head>
<body>
<div id="select">
<form>
<select onchange="selectFunction(this.value)">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</form>
</div>
</body>
</html>
Upvotes: 1
Reputation: 11052
Not sure what the problem is, is it because when the select
div is populated with the letter selection that the select
element is lost?
If so, you could have a dedicated element to store the selection:
<div id="select">
<div id="result">Selection will appear here</div>
<form>
<select onchange="selectFunction(this.value)">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>E</option>
</select>
</form>
<script type="text/javascript">
function selectFunction(letter){
document.getElementById("result").innerHTML = "Selection is : " + letter;
}
</script>
</div>
It might also be handy to add the value
to your options, e.g.
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
and lastly, adding an empty option since the change event won't work for A
because it is the first option, you'd have to select another option then select A
again.
<option value="">Select letter:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
Upvotes: 1