Fabio Fabio - 5 months ago 47
Javascript Question

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.

Answer

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