tags:

views:

34

answers:

2

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);
}).keyup();

$("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);
    });
 });
+3  A: 

$("#test").val(colWidth)

Topera
Am I doing something wrong in my above code while trying to get the data? I now recieve a NaN in the #test input field.
Louis Stephens
Topera - This wouldn't give any different result from the code in the question `$("input#test").val(colWidth)`
patrick dw
@patrick - When I answer the question, the question didn't have the code. :)
Topera
Topera - Ah, I see. Didn't realize that. Sorry about that. :o)
patrick dw
+1  A: 

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.

patrick dw
Oh. Ok. (I do apologize, I am still trying to learn the in/outs of jquery).. If I may ask, in your opinion, how do I rectify this?
Louis Stephens
@Louis - You need to trigger the calculation *after* the user has given some input into the fields. In your question, you used a `.click()` event on an `<a>` element. That would work just fine. Just provide `<a id="calc">calculate</a>` in your HTML, and put your calculation in the handler like you did above.
patrick dw
@Patrick dw, thanks.. It basically was staring me in the face *palm to forehead*
Louis Stephens
@Louis - You're welcome. :o)
patrick dw