Hoser
Hoser

Reputation: 5044

Javascript set attribute using variable

I'm unsure of the syntax here, but the code I have so far is this... (Note: I am passing the id's of three textboxes in the form '#begmile','#endmile','#totmile', and I want to set the value of the 'totmile' checkbox to endmile-bigmile)

function subtract(begmile, endmile, totmile){
y=$(begmile).attr('value');
z=$(endmile).attr('value');
y=z-y;
$(totmile).setAttr('value',???);

}

I'm not sure if my syntax here so far is correct, but assuming it is (that y is properly set to endmile-begmile, how do I use setAttr to set the value of totmile to the value of y?

Upvotes: 2

Views: 9881

Answers (3)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

The value attribute refers to the default value for the textbox, not the current one. The current one is stored in the value property.

function subtract(begmile, endmile, totmile) {
    document.getElementById(totmile).value =
      document.getElementById(endmile).value - document.getElementById(begmile).value;
}

This also removes the need for jQuery, since the JavaScript Sledgehammer is far too excessive for this job. To make sure it works, just remove the # when you pass IDs to the function.

Upvotes: 0

scunliffe
scunliffe

Reputation: 63578

your last line isn't calling the right method:

$(totmile).setAttr('value',???);

should be:

$(totmile).attr('value',???);

e.g.

$(totmile).attr('value', y);//set the value to the variable "y"

you can also call .val(); instead to easily get the value of a field, or .val(newValue); to set the value.

also note that if your values for "y" and "z" are not actually representing numbers you'll get a weird result.

Upvotes: 1

ioseb
ioseb

Reputation: 16951

This is the correct syntax:

var href = 'http://cnn.com';

$(selector).attr('href', href);

Upvotes: 4

Related Questions