Set Value of form input from variable in Jquery
I have a variable named colWidth in jquery which runs some math on numbers grabbed from an input using jquery. How do I set a value of an input field with an id of #test to the value of colWidth?
$("input#width").keyup(function () {
var value = $(this).val();
$("span#width-text").text(value);
}).key开发者_运维知识库up();
$("input#columns").keyup(function () {
var value = $(this).val();
$("span#columns-text").text(value);
}).keyup();
$("input#gutter").keyup(function () {
var value = $(this).val();
$("span#gutter-text").text(value);
}).keyup();
$("input#gutter").keyup(function () {
var value = $(this).val();
$("span#gutter-text").text(value);
}).keyup();
$(function(){
$('a#calc').click(function(){
var width = $('input#width').val();
var col = $('input#columns').val();
var gutter = $('input#gutter').val();
var newWidth = width / col;
var colSize = (gutter + gutter) * col;
var colWidth = newWidth - colSize;
$('input#test').val(colWidth);
});
});
$("#test").val(colWidth)
Louis,
You're getting NaN
because your calculation is running before the user has a chance to enter any numbers into the <input>
elements.
In your question, you use a .click()
handler to fire the calculation, but on your page, you don't. It just runs when the page loads.
Therefore the result of .parseInt()
is NaN
, and the result of the calculations are the same.
精彩评论