简体   繁体   中英

How to set value of input number with jQuery?

I'm trying to set the value of an input element using jQuery.

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

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. But I have to use number as input type.

How can I set the input value with jQuery or regular JavaScript?

Important notes

I tried to use year.val(ev.date.getFullYear()); but It didn't work.

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

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

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

You have to use the val function.

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

format: " yyyy"

to :

dateFormat: "yy"

(If you are using jquery-ui datepicker)

DEMO Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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