Reputation: 531
I have a drop down list, put together the simple way. What I'm looking to do is have it set for when the option "Other" is selected, a text box will show up and people can type in what they want. How can I accomplish this with the implementation of drop down list I have? Here is my drop down list code:
<div class="frm_label">
@Html.LabelFor(Model => Model.JobTitle)
</div>
<div class="item">
@Html.DropDownListFor(Model => Model.JobTitle, new SelectList(
new List<object>{
new { value = 0 , text = "Physician" },
new { value = 1 , text = "Researcher" },
new { value = 2 , text = "Clinical Staff" },
new { value = 3 , text = "Other" },
},
"value",
"text",
0))
</div>
Upvotes: 1
Views: 2185
Reputation: 101
I did something similar not to long ago, check out this fiddel http://jsfiddle.net/ItaySidis/QNXEZ/3/
the idea is to create a trigger when the select box changes to the "other" option, then you append a new input box with the same name attribute as the select box, and also hide the select and change the name to an empty string.
$('#jobTitle-select').change(function(){
if($(this).val() == 3) {
var input = $('<input type="text" name="jobTitle" id="new-jobtitle" placeholder="Enter your job title..." />');
$(this).attr('name','').addClass('hidden');
$('#back-to-list').show();
$(this).parent().append(input);
}
});
I also gave the user the option to go back and select from the list by clicking on the "go back to the list" span that does the exact opposite of the change event.
$('#back-to-list').click(function(){
$('#jobTitle-select').removeClass('hidden')
.attr('name','jobTitle')
.find('option:first')
.attr('selected','selected');
$('#new-jobtitle').remove();
$(this).hide();
});
hope it was clear enough..play with the fiddel you'll get the idea
Upvotes: 0
Reputation: 3630
Use this:
var dependentvalue = $('#JobTitle').val();
var field = $('#freetextfield');
if (dependentvalue === "3") {
field.removeClass('hidden');
}else{
field.addClass('hidden');}
where html is like this:
<div class="hidden">
@Html.TextBoxFor(model => model.freetextfield) // create this property of type string
</div>
in the controller, you can check if the value of the dropdownlist property is for another then validate this free text field.
css for .hidden:
.hidden {
display: none;
visibility: hidden;
}
Upvotes: 2