tags:

views:

25

answers:

3

How do I prefix a - sign for all the values entered in a textbox in javascript onblur

+1  A: 

First, you'll need to add the event handler. Once you do that, this is your function:

function textBoxBlur(e) {
    var evt = e || window.event;
    var tb = evt.target || evt.srcElement
    if (tb.value.indexOf('-') === -1) {
        tb.value = '-' + tb.value;
    }
}
Gabriel McAdams
A: 

If you use jQuery, which I highly recommend, you can:

$('#id-of-textbox').bind('blur', function() {
    $(this).val('-' + $(this).val());
});

Put this in a <script> tag at the end of your html.

With jQuery you can now add this functionality to any textbox you want this behavior. Go http://jquery.com/ for more info.

shoebox639
+1  A: 

Usign jquery you can:

$(selector).blur(function (){
  $(this).val("-"  +$(this).val());
});

With bare javascript is easy too:

document.getElementById("a").onblur = function (){
  this.value = "-" + this.value;
}

Don't forget to bind this events after window loads.

window.onload = function (){
  /* here */
}
madeinstefano