Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  75] [ 6]  / answers: 1 / hits: 36277  / 9 Years ago, thu, august 6, 2015, 12:00:00

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


More From » jquery

 Answers
17

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.


[#65512] Tuesday, August 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;