I have a form with a select element that contains a list of categories populated from an external source. When I submit the form I want to be able to post parameters for the value for the option selected (category_id), this works as expected. However I also want to pass a second parameter (category_name) which is currently the text of the select option.
For the sake of clarity below is a very simple representation of the select element:
<select name="category_id" id="category_id">
<option value='1'>All</option>
<option value='2'>Category 1</option>
<option value='3'>Category 2</option>
</select>
I was wondering what the best way of doing this is. Do I need to use Javascript or is there some way of doing this via 开发者_JAVA百科HTML? For what its worth Im using Rails to build the app so if there is a smart way to do this using the framework that would also be very useful to know.
Thanks in advance for the help.
Dave
You could either change the value so it contains both values then just split them on the server:
<select name="category_id" id="category_id">
<option value='1|All'>All</option>
<option value='2|Category 1'>Category 1</option>
<option value='3|Category 2'>Category 2</option>
</select>
Or use some javascript and update a hidden field:
HTML
<select name="category_id" id="category_id">
<option value='1'>All</option>
<option value='2'>Category 1</option>
<option value='3'>Category 2</option>
</select>
<input type="hidden" id="category_name" name="category_name" />
JS
function updateNameValue() {
$('#category_name').val($('#category_id option:selected').text());
}
$('#category_id').change(updateNameValue);
updateNameValue(); // Call function here to make sure initial value is set
http://jsfiddle.net/6runZ/
精彩评论