views:

42

answers:

3

Hi,

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.

The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.

Any ideas as to how I could implement this?

Thanks

Zaps

+1  A: 

First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.

Number.prototype.bracketed = function() {
    if(this < 0) {
        return '[' + -this + ']';
    } else {
        return '' + this;
    }
};

var result = do_calculation();

myTextBox.value = result.bracketed();

// result still holds the original Number value.

If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:

String.prototype.unbracketed = function() {
    var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number

    if(parts[1]) {  // [number]
        return -parseInt(parts[1], 10);
    }

    if(parts[2]) {  // number
        return parseInt(parts[2], 10);
    }

    return NaN;
};
strager
+2  A: 
function FormatTextBox(id) {
  var txtBox = $(id).val();
  //strip bracket to get the number only
  txtBox = txtBox.replace("[", "").replace("]", "");
  var val = parseFloat(txtBox);

  if (val < 0) {
    txtBox.val("[" + val + "]");
  } else {
    txtBox.val(val);
  }
  return val;
}
A: 

Assuming you might have multiple fields (and you don't want the negative sign):

jQuery('input').each(function(){
        if(jQuery(this).val() < 0 ){ 
            jQuery(this).val('['+-1*jQuery(this).val()+']');
        }
    }
)

Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.

EDIT:

You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Aaron Harun
Instead of .each, you could use .change in order to make it happen on the fly. But then again, you'll probably need some code to account for any numbers inside brackets.
Gert G