I'm trying to show a different form field based on an option id in my form (not the value), but I get the same/double results no matter what is selected.
When I Choose Rent I get:
When I Choose Own I get:
What do I need to do to fix this?
function rentown(nameSelect)
{
if(nameSelect){
rentcheck = document.getElementById("rentcheck").value;
//alert(admOptionValue);
if(rentcheck == document.getElementById("rentcheck").value){
document.getElementById("rent").style.display = "block";
}
else{
document.getElementById("rent").style.display = "none";
}
}
if(nameSelect){
owncheck = document.getElementById("owncheck").value;
if(owncheck == document.getElementById("owncheck").value){
document.getElementById("own").style.display = "block";
}
else{
document.getElementById("own").style.display = "none";
}
}
}
<select onchange="rentown(this);">
<option selected="true" disabled="disabled">Please Choose</option>
<option id="rentcheck" value="0">Rent</option>
<option id="owncheck" value="0">Own</option>
</select>
<div id="rent" style="display:none;">
rent selected
</div>
<div id="own" style="display:none;">
own selected
</div>
You might want to check the selected option id
function rentown(nameSelect)
{
if(nameSelect){
var selectedOption = nameSelect.options[nameSelect.selectedIndex];
if(selectedOption.id === "rentcheck"){
document.getElementById("rent").style.display = "block";
}
else{
document.getElementById("rent").style.display = "none";
}
if(selectedOption.id === "owncheck"){
document.getElementById("own").style.display = "block";
}
else{
document.getElementById("own").style.display = "none";
}
}
}
<select onchange="rentown(this);">
<option selected="true" disabled="disabled">Please Choose</option>
<option id="rentcheck" value="0">Rent</option>
<option id="owncheck" value="0">Own</option>
</select>
<div id="rent" style="display:none;">
rent selected
</div>
<div id="own" style="display:none;">
own selected
</div>
You need to find the selected option, which you can do by giving each option a different value and looking at the select element's value - just checking the options' static values in the HTML won't show any change.
const rent = document.querySelector('#rent');
const own = document.querySelector('#own');
function rentown() {
const sel = document.querySelector('select').value;
if (!sel) return;
if (sel === 'rentcheck') {
rent.style.display = 'block';
own.style.display = 'none';
} else {
rent.style.display = 'none';
own.style.display = 'block';
}
}
<select onchange="rentown();">
<option selected="true" disabled="disabled">Please Choose</option>
<option id="rentcheck" value="rentcheck">Rent</option>
<option id="owncheck" value="owncheck">Own</option>
</select>
<div id="rent" style="display:none;">
rent selected
</div>
<div id="own" style="display:none;">
own selected
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With