简体   繁体   English

如何使用jQuery设置输入数字的值?

[英]How to set value of input number with jQuery?

I'm trying to set the value of an input element using jQuery. 我正在尝试使用jQuery设置输入元素的值。

HTML: <input id="id_year" name="year" type="number"> HTML: <input id="id_year" name="year" type="number">

JavaScript: JavaScript:

$(document).ready(function () {
    var year = $("#id_year");
    year.datepicker({
        format: " yyyy", // Notice the Extra space at the beginning
        viewMode: "years", 
        minViewMode: "years"
    });
    year.on('changeDate', function(ev){
        year.attr('value',ev.date.getFullYear());
    });
});

If the input type is text , it works. 如果输入类型为text ,则可以使用。 But I have to use number as input type. 但是我必须使用number作为输入类型。

How can I set the input value with jQuery or regular JavaScript? 如何使用jQuery或常规JavaScript设置输入值?

Important notes 重要笔记

I tried to use year.val(ev.date.getFullYear()); 我试图使用year.val(ev.date.getFullYear()); but It didn't work. 但这没用。

year.val(ev.date.getFullYear());

to get the value: var yearValue = year.val(); 获取值: var yearValue = year.val();

http://api.jquery.com/val/ http://api.jquery.com/val/

You have to use the val function. 您必须使用val函数。

You can write your code as this: 您可以这样编写代码:

$(document).ready(function () {
    var year = $("#id_year");
    year.datepicker({
        format: " yyyy", // Notice the Extra space at the beginning
        viewMode: "years", 
        minViewMode: "years"
    });
    year.on('changeDate', function(ev){
        console.log("ssds");
        $(this).val(ev.date.getFullYear());
    });
});

You can use like this. 您可以这样使用。

 $(document).ready(function () { var year = $("#id_year"); year.datepicker({ format: " yyyy", // Notice the Extra space at the beginning viewMode: "years", minViewMode: "years", onSelect: function(dateText) { console.log(dateText); var startDate = new Date(dateText); year.val(startDate.getFullYear()); console.log(year.val()); } }); /* year.on('changeDate', function(ev){ console.log("ssds"); year.val(ev.date.getFullYear()); console.log(year.val()); });*/ }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css"> <input id="id_year" name="year" type="number"> 

Your code is right, just the definition of datepicker is wrong, change 您的代码是正确的,只是datepicker的定义是错误的,请更改

format: " yyyy"

to : 至 :

dateFormat: "yy"

(If you are using jquery-ui datepicker) (如果您使用的是jquery-ui datepicker)

DEMO Here 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM