问题
I have a select element with a couple of dates but I also want to give the possibility of picking a date from the datepicker so I have the following code that displays a calendar icon next to the select field.
<select name="birthday" >
<option value="${merge0.birthday}">${merge0.birthday}</option>
<option value="${merge1.birthday}">${merge1.birthday}</option>
</select>
<input type="hidden" id="bday_icon" />
Then, this is my datepicker script
$("#bday_icon").datepicker(
{
changeMonth: true,
changeYear: true,
showOn: 'button',
buttonImage: 'cal/images/calendar.gif',
buttonImageOnly: true,
onSelect: function(dateText, inst) {
var field = document.getElementsByNameByName("birthday");
var opt = document.createElement('option');
opt.text = dateText;
opt.value = dateText;
field.add(opt, null);
}
});
Shouldn't the function onSelect, add a new option to the select html element? can't you see what it's wrong?
Thanks.
Update 1:
onSelect: function(dateText, inst) {
var opt = $('<option />').attr('value', dateText).text(dateText);
$('select[name=birthday]').append(opt);
}
Works perfect, only remark that I needed to mark as selected the new option so just edit like: $('<option selected/>')
回答1:
Unless they're some of your functions, I'm not really sure what .add()
and getElementsByNameByName()
are. I can't seem to find add
in the jQuery api.
Also, when working with jQuery widgets, I prefer to use jQuery selectors:
onSelect: function(dateText, inst) {
var opt = $('<option />').attr('value', dateText).text(dateText);
$('select[name=birthday]').append(opt);
}
Works for me.
来源:https://stackoverflow.com/questions/2100605/jquery-ui-datepicker-on-select-element