Search code examples
asp.nethtmltextboxplaceholder

Time type and placeholder in html5


How can I set a placeholder in a textbox with type="time"? Currently, it displays the time input format like --:--, but I'd like it to show "Start Time" and "End time" inside the textbox itself, not on an external label.

<asp:TextBox ID="StartingHour" Type="time" runat="server" placeholder="Start Time" required="required" />

Right now, it displays --:-- instead of the placeholder text. Any suggestions?


Solution

  • The placeholder attribute setting depends on how the client browsers behave with <input type="time" />, but if you want to show placeholders when the user not selecting input control, you may try this workaround:

    ASPX

    <asp:TextBox ID="StartingHour" runat="server" placeholder="Start Time" required="required" />
    

    JS (jQuery)

    // when getting focus
    $('#<%= StartingHour.ClientID %>').focus(function () {
        $(this).attr('type', 'time'); 
    });
    
    // when losing focus
    $('#<%= StartingHour.ClientID %>').focusout(function () {
        $(this).attr('type', 'text'); 
    });
    

    Note: The same way can be used for control EndingHour's placeholder.

    JSFiddle Example

    Update 1:

    If you want to use common prefix (like txtHour) to input controls, you may set ClientID mode to Static and use the prefix as selector:

    <asp:TextBox ID="txtHour1" runat="server" ClientIDMode="Static" placeholder="Time" required="required" />
    
    <asp:TextBox ID="txtHour2" runat="server" ClientIDMode="Static" placeholder="Time" required="required" />
    

    JS (jQuery)

    // when getting focus
    $('input[id^="txtHour"]').focus(function () {
        $(this).attr('type', 'time'); 
    });
    
    // when losing focus
    $('input[id^="txtHour"]').focusout(function () {
        $(this).attr('type', 'text'); 
    });
    

    Or use a shared CSS class assigned for all related textbox controls:

    <asp:TextBox ID="txtHour1" runat="server" CssClass="hour" placeholder="Time" required="required" />
    
    <asp:TextBox ID="txtHour2" runat="server" CssClass="hour" placeholder="Time" required="required" />
    

    JS (jQuery)

    // when getting focus
    $('.hour').focus(function () {
        $(this).attr('type', 'time'); 
    });
    
    // when losing focus
    $('.hour').focusout(function () {
        $(this).attr('type', 'text'); 
    });
    

    Similar issue: Can I use placeholder in <input type="time"/>