In: Computer Science
Using form events functions to answer this question. Use the attached form html file which contains 2 html radio buttons. When the first choice is chosen, display the text ”First” under the first choice. When the second choice is chosen, display the text ”Second” under the second choice. Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>midterm exam</title>
<link rel="stylesheet" href="css/q1.css"
/>
</head>
<body>
<div id = "page">
<form>
<input type="radio"
id="first" name="midterm" value="first">
<label
for="first">First</label><br>
<input type="radio"
id="second" name="midterm" value="second">
<label
for="second">Second</label><br>
</form>
</div>
<script
src="js/q4.js"></script>
</body>
</html>
Answer) The code for the above question is below: Save this file with name q4.js inside js folder. Confirm the src path as you have given in HTML script src tag.
// getting first and second buttons
first_radio=document.getElementById("first");
second_radio=document.getElementById("second");
// creating a label element for first to display
var label_first = document.createElement("label");
var node1 = document.createTextNode("First");
// creating a label element for second to display
var label_second = document.createElement("label");
var node2 = document.createTextNode("Second");
// adding event Listener to first radio so that when it is clicked it displays label
first_radio.addEventListener('change', function(){
this.after(node1);
});
// adding event Listener to second radio so that when it is clicked it displays label
second_radio.addEventListener('change', function(){
this.after(node2);
});
CODE SCREENSHOT
OUTPUT: Here you can see when we click first another label first is displayed. If you want to display first one time remove the label from the HTML file.