Skip to content Skip to sidebar Skip to footer

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><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></head><body><labelfor="vals">Choose</label><selectname="vals"id="vals"onchange="updateDisplay(this.value)"><optionvalue="1"selected>1</option><optionvalue="2">2</option><optionvalue="3">3</option></select><divid='row1'><p>this is row 1</p></div><divid='row2'style="display:none;"><p>this is row 2</p></div><divid='row3'style="display:none;"><p>this is row 3</p></div><script>constupdateDisplay = (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?"