Koosh
Koosh

Reputation: 896

is it possible to change the value in a dropdown using Javascript when dropdown is disabled

I have a web form where i disable a dropdown on page load in C#.

The drop down is to be disabled at all times, only when users make a certain selection is when I would like to change the value in my drop down. Either Yes or No.

This is my Javascript code:

    var drpModeNeed = document.getElementById("drpAssessID"); //This dropdown is 
               //where I'm looking to change the value (it is disabled)

    var drp4Val = (document.getElementById('<%=drp4ID.ClientID %>').value);
    var drp14Val = (document.getElementById('<%=drp14ID.ClientID %>').value);
    var drp15Val = (document.getElementById('<%=drp15ID.ClientID %>').value);

    if (drp4Val == 1 || (drp14Val == 1 && drp15Val == 1)) 
    {
        //trying to change the value here of dropdown
    }

This is what I've tried in the if statement

    drpModeNeed.options[drpModeNeed.selectedIndex].value == 1;

but nothing happens. I know for sure that it definitely recognizes the statements, becase I've placed an alert inside the IF statement and each time it would show that the values were definitely selected.

I guess I'm wondering if I'm able to change the value of a disabled dropdown? if I am, then why isn't the code working?

Upvotes: 0

Views: 80

Answers (2)

Milko
Milko

Reputation: 71

it works for me:

	function changeValue(newValue){
		var drpModeNeed = document.getElementById("drpAssessID");
		drpModeNeed.value=newValue;
	}
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>

<select id="drpAssessID" disabled="disabled" class="aspNetDisabled">
	<option value="1">one</option>
	<option selected="selected" value="2">two</option>
</select>
<br /><br />
<button type="button" onclick="changeValue(1);">Set 1</button>
<br /><br />
<button type="button" onclick="changeValue(2);">Set 2</button>


</body>
</html>

Upvotes: 1

Pointy
Pointy

Reputation: 413720

To update the effective value of a <select> element, you don't set the .value of an <option>, you set the .selected property to true (or any truthy value):

drpModeNeed.options[1].selected = true;

Keep in mind that if the <select> element has the .disabled property set, posting the enclosing <form> will not send that value to the server. The browser assumes that disabled elements are supposed to be ignored.

Upvotes: 1

Related Questions