Reputation: 105
The code below works just fine, but now I have to make date picker appear when I select a defined option from the select list> Let's use something like this, for example:
$(function() {
$('#date').datepicker({
dateFormat: 'dd-mm-yy',
altField: '#thealtdate',
altFormat: 'dd-mm-yyyy'
});
});
function showDP(cbox){
if (cbox.checked) {
$('#date').css({
display: "block"
});
} else {
$('#date').css({
display: "none"
});
}
}
<input type="checkbox" id="DPenable" onClick="showDP(this);">
<input id="date" type="text" style="display:none"/>
<select>
<option id='1'>1</option>
<option id='2'>2</option>
<option id='3'>3</option>
</select>
The Date picker should appear when I select option 2 and disappear when I change it to 1 or 3. I tried many solutions and selectors, etc., but nothing was working how it was supposed to (I was probably doing something wrong, I'm pretty new in JS). Can anyone please point me to online resources or provide advice on how I might achieve this? Thanks.
Upvotes: 0
Views: 2154
Reputation: 9794
Try like this...
onchange event of select you can make bind the function to display the datepicker based on the current value of the select,
$(function() {
$('#date').datepicker({
dateFormat: 'dd-mm-yy',
altField: '#thealtdate',
altFormat: 'dd-mm-yyyy'
});
});
function showDP(cbox){
if (cbox.checked) {
$('#date').css({
display: "block"
});
}else{
$('#date').css({
display: "none"
});
}}
function showDPNew(select)
{
if ($(select).val() == 2) {
$('#date').css({
display: "block"
});
$("#date").focus();
}
else{
$('#date').css({
display: "none"
});
$("#date").blur();
}}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<select onChange="showDPNew(this)">
<option id='1'>1</option>
<option id='2'>2</option>
<option id='3'>3</option>
</select>
<input id="date" type="text" style="display:none"/>
Plunker : https://plnkr.co/edit/SxRHSd497Xk20Gxm9RqU?p=preview
Upvotes: 2
Reputation: 4515
You just need to watch for change on the select. When it changes, you can check the selected option's id. In place of the console.log()
, you can continue using .css()
to change the display of your datepicker.
$('select').on('change', function() {
if($(this).find('option:selected').prop('id') == 2)
console.log('datepicker is displayed');
else
console.log('datepicker is hidden');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id='1'>1</option>
<option id='2'>2</option>
<option id='3'>3</option>
</select>
Upvotes: 1