3

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

3 Answers 3

2
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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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;
};

Comments

0

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/ )

1 Comment

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.

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.