6

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

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

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

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

我已经尝试过:

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

但无济于事。

4

2 回答 2

1

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

您将无法使用 HTML5 日期字段,但这可以通过 jQuery UI 日期选择器来完成。 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>

于 2014-10-21T20:40:33.513 回答
1

日期类型不支持占位符属性。 此外,WebKit 实现说它是固定的。

于 2012-10-13T01:58:27.473 回答