Home > Mobile >  Font awesome icon in jquery date picker
Font awesome icon in jquery date picker

Time:07-12

I am trying to display the fontawesome icon on "buttonText" of jquery date picker but it displays the text and not the icon. Is it correct? I am using jquery 13.

$("#btnDate").datepicker({
            showOn: "button",
            buttonText: "<i class='fa fa-calendar'></i>",
            onSelect: function (selected) {
            }
        });

CodePudding user response:

You could add the icon after setting the datepicker :

$("#btnDate").datepicker({
    showOn: 'button',
    buttonText: "",
}).next('button').append('<i ></i>');
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script>
<p>Date: <input type="text" id="btnDate"></p>

CodePudding user response:

Datepicker created an element:

<img  />

When you define the Text, it is added to the alt and title attributes. Like so:

<img  src="images/calendar.gif" alt="Select date" title="Select date">

This is why your attempt is not working.

A click event is assigned to this that opens the datepicker. Since it's an image, you can't simply assign a Font Awesome Class to it.

Consider the following.

$(function() {
  $("#datepicker").datepicker({
    showOn: "button",
    buttonImageOnly: true,
    buttonText: "Select date"
  });

  var newButton = $("<span>", {
    class: "ui-datepicker-trigger fa fa-calendar"
  }).click(function() {
    $(this).toggleClass("closed");
    if ($(this).hasClass("closed")) {
      $("#datepicker").datepicker("show");
    } else {
      $("#datepicker").datepicker("hide");
    }
  });

  $("img.ui-datepicker-trigger").replaceWith(newButton);

});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>

<p>Date: <input type="text" id="datepicker"></p>

Using .replaceWith() will do what you need to have done. It will not copy the event, so we have to recreate it.

  • Related