views:

35

answers:

3

I have a javascript function that changes a user preference, if they want weights to be metric or in imperial.

On my page I print out the weight, IE:

This is some description:

This product weights <b>200 KG</b>

Blah blah

I need to make it so that Javascript changes the weight measurement for all weights on the page, and am not sure the best way to tackle this. Can you create your own tags, or tag properties?

Thanks for any suggestions, JQuery is fine.

+4  A: 

I would add a class .weight and use this to target all the weights..

$('.weight').each(function(){...})

If you want to change the innerHTML you can use the html() method directly

$('.weight').html(function(idx, oldhtml){
 // you can use the oldhtml to extract info and create the new text here..
  $(this).html( ../*you new html here*/.. ); // replace existing with new html ..
})
Gaby
Thanks, pretty new to Jquery, how do you access the inner HTML of each weight div? I should be ok from there
Tom Gullen
@Tom, added some code to change the html ..
Gaby
@Tom, note that @T.J. Crowder has provided a complete solution at the end of his answer.
Gaby
+5  A: 
T.J. Crowder
Thanks for the great answer, but I get the error: "Error: $("[data-weight]") is null" when I try and run this in "the jQuery(document).ready(function() {" function
Tom Gullen
@Tom: Try to run it where? It works on JSBin. Tested on Chrome, Firefox, and Opera on Linux, and IE6 (!) and IE8 on Windows, I figure if all of those work, it should be pretty cross-browser... :-) If you're doing it on your own site, did you include jQuery? The above assumes you're using it, since you said that was okay in the question.
T.J. Crowder
Thanks Crowder, yes I am using Jquery, I'll do a new question for it though as it's a different problem
Tom Gullen
@Tom: Ah, gotcha. Good luck!
T.J. Crowder
@Tom: Added a note about performance. You probably won't see an issue, but for the sake of completeness...
T.J. Crowder
+1  A: 

HTML:

<b class="weight">200 KG</b>

Javascript:

$("#UnitChangeButton").click(function() {
  $('.weight').each(function(){
    txt = $(this).text();
    newTxt = convert(txt);
    $(this).text(newTxt);
  });
});

You need to implement the convert function. You can store the state (metric or imperial) in a javascript variable.

kgiannakakis