Reputation: 1289
Right now,
I have the below jquery, css and html code which works the way i want. Where If the user selects a dropdown a certain textbox shows. But how can I do it easily in rails?
HTML
<form>
<select id="sel">
<option value="">- select -</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="other">Other</option>
</select>
<label id="label1" for="option1">Text box label 1
<input type="text" id="option1" />
</label>
<label id="label2" for="option2">Text box label 2
<input type="text" id="option2" />
</label>
<label id="label3" for="option3">Text box label 3
<input type="text" id="option3" />
</label>
<label id="label4" for="option4">Text box label 4
<input type="text" id="option4" />
</label>
<label id="label5" for="option5">Other
<input type="text" id="option5" />
</label>
</form>
CSS
label {
display:block;
}
JQUERY
$(function() {
//This hides all initial textboxes
$('label').hide();
$('#sel').change(function() {
//This saves some time by caching the jquery value
var val = $(this).val();
//this hides any boxes that the previous selection might have left open
$('label').hide();
//This just opens the ones we want based off the selection
switch (val){
case 'option1':
$('#label1').show();
break;
case 'option2':
$('#label2').show();
break;
case 'option3':
$('#label1').show();
break;
}
});
});
Rails code
<%= f.select(:title, ["Select an option","Option 1", "Option 2", "Option 3"])%>
But I am unsure as to how to show the text box. And the select options I only 3 here. But in my application there will like 10-15.
Thanks
Upvotes: 1
Views: 2554
Reputation: 54882
You should use a convention between your options and the HTML ids to display.
If your options have a static value, matching an existing label, you could do:
$(function() {
$('label').hide();
$('#sel').change(function() {
var val = $(this).val();
$('label').hide();
$('#label'+val).show():
});
});
With this you would not have to handle each option, but just add the corresponding option/label id.
Upvotes: 1
Reputation: 256
Instead of hardcoding the IDs, try to grab the selectedIndex property of the dropdown; indexes start at 0 (zero)
var i = getElementById('sel').selectedIndex ;
$('#label'+i).show();
$('#option'+i).show();
this is scalable, so it will work if you add options in the future.
Upvotes: 0