I'm trying to develop a form where fields will be show according to already selected fields.
I'm facing problem to integrate JavaScript with html properly. I need your help to let me know how I can update the display of fields asynchronously.
Expected Behavior : By default there will 1 choice selected and 1 input field , if user selects 2 choices from select input then there should be 2 input fields
This is minimal example where I'm trying:
document.getElementById("app").innerHTML = `
<h1>Show fields According to Selected Choice</h1>
<div>
1 field if selected one choice
2 fields if selected 2 choices
</div>
`;
body {
font-family: sans-serif;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<fieldset>
<div class="form-row field-type">
<div>
<label class="required" for="id_type">Select Choices:</label>
<select name="type" id="id_type">
<option value="1" selected>1 Choice</option>
<option value="2">2 Choices</option>
</select>
</div>
</div>
<div>
<label for="id_choice_1">Choice 1:</label>
<input
type="text"
name="choice_1"
class="vTextField"
maxlength="100"
id="id_choice_1"
/>
</div>
<div>
<label for="id_choice_2">Choice 2:</label>
<input
type="text"
name="choice_2"
class="vTextField"
maxlength="100"
id="id_choice_2"
/>
</div>
</fieldset>
<script>
function myFunction() {
var x = document.getElementById("id_type").value || null;
// Put logic here
}
</script>
<script src="src/index.js"></script>
</body>
</html>
I also added this into a sandbox if you want to run the code. https://codesandbox.io/s/fervent-worker-r6xszj?file=/src/index.js