1

I'm working on small web form where I need to display number in the text field's as currency format in bootstrap appended addon.

I'm able to achieve for a single field using jQuery selectors (I'm new to Javascript world), I wanted to do the same thing for aroung 10 fields.

I think there must be elegant solution rather than writing the same for every field.

Kindly help me.

My HTML Code:

<div class="control-group">
    <label class="control-label">Loan Amount 1</label>
    <div class="controls">
        <div class="input-append">
            <input class="span2" id="loanAmount1" type="text">
            <span class="add-on" id="loanAmount1Cur">$</span>
        </div>
    </div>
</div>
<div class="control-group">
    <label class="control-label">Loan Amount 2</label>
    <div class="controls">
        <div class="input-append">
            <input class="span2" name="loanAmount2" type="text">
            <span class="add-on" name="LoanAmount2Cur">$</span>
        </div>
    </div>
</div>

My JS Code:

$(document).ready(function () {
        $("#loanAmount1").on("keyup", null, function () {
            var input = $("#loanAmount1").val();
            var num = parseFloat(input).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + " $";
            $("#loanAmount1Cur").html(num);
        });
    });

My JSFiddle: http://jsfiddle.net/kiranm516/me52djL8/24/

I copied the above code from (thanks to them): Add comma to numbers every three digits

Community
  • 1
  • 1
Kiran Marturu
  • 115
  • 2
  • 4
  • 12

1 Answers1

4

Assign a class to your inputs, and then bind the keyup event to your class, rather than to an ID.

Forked your JSFiddle: http://jsfiddle.net/zmbh4o2u/

JS:

$(document).ready(function () {
    $(".loan-input").on("keyup", null, function () {
        var $input = $(this),
            value = $input.val(),
            num = parseFloat(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

        $input.siblings('.add-on').text('$' + num);
    });
});

Helpful tips:

  1. In the handler function for your keyup event, you can access the element that fired the event with this. Since you'll need that element a couple of times, it's customary to cache a jQuery object in a local var, hence var $input = $(this).
  2. When declaring multiple variables in JavaScript, it's best practice to chain them in a single var statement. You can comma separate your declarations, and use line breaks for legibility.
benjarwar
  • 1,794
  • 1
  • 13
  • 28
  • But, I wanted to add the currency format to the addon (span tag), I don't wanna change the input text. like [This First Field](http://jsfiddle.net/me52djL8/31/) the first field in this – Kiran Marturu Aug 06 '15 at 17:43
  • Simple! Use $.siblings() to find the ```.add-on``` element adjacent to the ```$input```. I have updated the code and the forked JSFiddle. – benjarwar Aug 06 '15 at 18:15
  • 4
    I'm getting a "spam detected" error for the jsfiddle. – Brian Sep 23 '16 at 17:04