How Can I Show Or Hide Rows Depending On A Value In Selectbox?
I have one SelectBox, it can have values as 1,2,3. Lets say This selectbox's name is : selectbox1. There are 3 rows. 1.row => There is selectBox named selectbox2, and textbox na
Solution 1:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<label for="vals">Choose</label>
<select name="vals" id="vals" onchange="updateDisplay(this.value)">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id='row1'>
<p>this is row 1</p>
</div>
<div id='row2' style="display:none;">
<p>this is row 2</p>
</div>
<div id='row3' style="display:none;">
<p>this is row 3</p>
</div>
<script>
const updateDisplay = (rowNumber) => {
for(let i=1;i<4;i++) $(`#row${i}`).hide(); // hide all rows
$(`#row${rowNumber}`).show();// show the required row
}
</script>
</body>
</html>
I have used jQuery's hide and show function to make the code look simpler. The same can be implemented using vanilla JavaScript as well like:
HIDE -> document.getElementById("row2").style.display = 'none';
SHOW -> document.getElementById("row2").style.display = 'block';
Post a Comment for "How Can I Show Or Hide Rows Depending On A Value In Selectbox?"