最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript set attribute using variable - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Sep 12, 2012 at 16:01 Niet the Dark Absol 325k85 gold badges474 silver badges599 bronze badges asked Sep 12, 2012 at 15:56 HoserHoser 5,0449 gold badges48 silver badges67 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

This is the correct syntax:

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

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

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.

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.

发布评论

评论列表(0)

  1. 暂无评论