I'm working on a project using jQuery to make a currency converter. I'm getting the currency info from an api service and loading it up in a table with multiple currencies. After which, I want to be able to enter a number in one input and make the other inputs produce the correct currency according to the entered input.
As you can see in the following code, I'm trying to make the keyup function work on everything but the input of which the numbers are being entered at that moment. My output result from the function is also incorrect.
If anyone can point out the very obvious mistake I'm making here that would be very helpful!
JS:
function parseCurrency(data) {
var container = $('.currency-data');
var iskInput = $('<tr>' +'<td>' + '<strong>ISK</strong>' +
'</td> ' + '<td>' + 'Íslensk króna' +
'</td>' + '<td></td>' + '<td>' + '1' + '</td>' +
'<td>' + '<input value="1000" class="input-value"></input>' + '</td>' +
'</tr>');
iskInput.prependTo(container);
$.each(data.results, function (key, currency){
var row = [];
row = $('<tr></tr>');
row.append('<td>' + '<strong>' + currency.shortName + '</strong>' + '</td>');
row.append('<td>' + currency.longName + '</td>');
row.append('<td>' + currency.changeCur + '</td>');
row.append('<td>' + currency.value + '</td>');
var input = $('<input class="input-value"></input>');
input.val((1000/currency.value).toFixed(2));
var td = $('<td></td>');
input.appendTo(td);
td.appendTo(row);
container.append(row);
})
var inputValue = $('.input-value');
var inputActive = $('.input-value:focus')
$.each(data.results, function (key, currency) {
inputValue.not(inputActive).keyup( function () {
inputValue.val((inputValue.val()/currency.value ).toFixed(2));
});
})
}
HTML:
<form name="converter"></div>
<h4>Collecting data from: <a href="" class="m5">m5</a> <a href="" class="arion">A bank</a> <a href="" class="lb">Lb</a></h4>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Obj1</th>
<th>Obj2</th>
<th>Obj3</th>
<th>Obj4</th>
<th>Obj5</th>
</tr>
</thead>
<tbody class="currency-data">
</tbody>
</table>
<div class="loader lead" style="display:none;">Loading...</div>
</form>
That's a bit strange for me, because you select all the input field which are NOT focused, and in the keyup eventhandler you just work with the inputValue variable, which contains the focused input element too. By the way, you shouldn't iterate two times on the data.results. As charlietfl commented before it does not make any sense to put the bindings to the iteration. That's a big mistake also.
A simple Method