开发者

Adding characters to string (input field)

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开发者_StackOverflow社区 ideas as to how I could implement this?

Thanks

Zaps


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜