如何更改Chrome中日期字段中显示的HTML5占位符文字

时间:2012-10-12 14:08:02

标签: jquery html5 datepicker placeholder datefield

我惊喜地发现以下代码在Chrome中查看时会呈现一个日期选择器:

<input type="date" name="wdate" id="wdate" value="" placeholder="date of purchase" />

但是,将忽略占位符文本,而是显示“日期/月/年”。

如何更改占位符文字并使用我自己的文字?

我已经尝试过了:

<script>
    $("#wdate").attr("placeholder", "Day/Month/Year of purchase");
</script>

但无济于事。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

较早的问题,但这是我最近必须使用的解决方案。

您将无法使用HTML5日期字段,但可以使用jQuery UI datepicker完成此操作。 http://jsfiddle.net/egeis/3ow88r6u/

var $datePicker = $(".datepicker");

// We don't want the val method to include placehoder value, so removing it here.
var $valFn = $.fn.val;
$.fn.extend({
    val: function() {
        var valCatch = $valFn.apply(this, arguments);
        var placeholder = $(this).attr("placeholder");
        
        // To check this val is called to set value and the val is for datePicker element 
        if (!arguments.length && this.hasClass('hasDatepicker')) {
            if (valCatch.indexOf(placeholder) != -1) {
                return valCatch.replace(placeholder, "");
            }
        }
        return valCatch;
    }
});

// Insert placeholder as prefix in the value, when user makes a change.
$datePicker.datepicker({
    onSelect: function(arg) {
        $(this).val($(this).attr("placeholder") + arg);
    }
});

// Display value of datepicker
$("#Button1").click(function() {
    alert('call val(): {' + $datePicker.val() + '}');
});

// Submit
$('form').on('submit', function() {
    $datePicker.val($datePicker.val());
    alert('value on submit: {' + $datePicker[0].value + '}');
    return false;
});
.ui-datepicker { width:210px !important; }
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/blitzer/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<form method="post">
    <p>HTML5 Date: <input type="date" placeholder="html5 date:" /></p>
    <p>jQuery DatePicker: <input type="text" class="datepicker" placeholder="Start date:" /></p>
    <p><input id="Button1" type="button" value="Get DatePicker Value" title="Get DatePicker Value" /></p>
    <p><input type="submit" text="fire submit" /></p>
    <p>Original Source for this <a target="_blank" href="http://jqfaq.com/how-to-add-some-custom-text-to-the-datepickers-text-field/">JQFaq Question</a></p>
</form>