1

My question is related to this topic here.

I would need a jquery replacement function for a number with a string as well, but much finer though.

My php returns a number in this format eg 1.27

Depending on a range this number should be replaced by a certain string that matches a range:

Example:

The number 1.27 is in the "active" range of 1.0 and 1.5, so the replacement for this would be the string "active". The value of 1.51 would be in the "less active" range from 1.5 to 2.0 and the replacement string would be the "less active" string.

Any ideas are much appreciated

1
  • Why not parse and deal with something like an if statement? Although solvable by regex it feels like it's not the correct tool for the job. Commented Apr 21, 2011 at 8:41

3 Answers 3

3

Accessing the text in the page can be done using jQuery, but the rest of the code is plain Javascript.

You can use a regular expression to find the number, then use a function that determines what to replace it with, something like this:

var element = $('#id');
element.text(element.text().replace(/[\d\.]+/g, function(s){
  var n = parseDouble(s);
  if (n >= 1.0) {
    if (n <= 1.5) return "active";
    if (n <= 2.0) return "less active";
  }
  return s;
}));
Sign up to request clarification or add additional context in comments.

Comments

1

Unfortunately you cannot do this with a single line of code. You'd have to do something like the following:

$(".number").each(function(){
    var elm = $(this);
    var number = parseFloat(elm.text(), 10);
    if (number >= 1 && number <= 1.5) {
        state = "active";
    } else if (number >= 1.5 && number < 2) {
        state = "less active";
    }
    elm.text(state);
});

See the above example on jsFiddle

2 Comments

In my case I need to use a class instead of an id due to to the dom. ATM this does not work of course link
@Christian Updated so that it works with multiple elements (classes)
-1

I dont understand what jQuery has to do with it, but this is pretty simple really...

var state = 'Default';
if(value > 1 && value < 1.5)
 state = 'Active';
else if(value < 2)  
 state = 'Less active';
else if(value < 3)
 state = 'Sleeping';

You might want to get a good book about programming, this really shouldnt be an issue.

1 Comment

this is not what he is asking. He wants " UserA - 1.27 : UserB - 1.51" to become " UserA - active : UserB - less active"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.