Reputation: 573
I'm creating a dinamically added input form. I want to make it so when an input loses the focus, its value get .00
appended to it. So far I tried this:
$(".money-input").on("click", function(e) {
e.stopPropagation();
});
$(document).on("click", function (e) {
$(".money-input").each(function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
});
My problem is, it only works when I click on other divs but inputs. Additionally what I also want to achieve is when I edited something on one input then switch focus to other input, the previous input value got appended by .00
.
Any help appreciated! :)
Upvotes: 0
Views: 693
Reputation: 43880
The requested behavior is odd...use the step
attribute instead:
<input type='number' step='01'>
The minimum requirements to have a floating point value in an input is to have: type="number"
and step
attributes. In the following Demo there are 3 forms with 2 inputs each for a total of 6 inputs.
The first 2 inputs have no step
attribute.
The second pair are dynamically created. The first input has no step
attribute whilst the second one does.
The last pair of inputs have the step
attribute.
I modified the styles so when an input has the step
attribute, its borders are red dashed lines. It's not necessary to do this, it's just for demonstration purposes.
There is a jQuery on event handler registered on 2 events, one is blur
event and the other is the change
event. These events trigger the same handler which will set the step
attribute to an input upon the triggering of either change
or blur
events.
$('#form1').append("<input id='i2' class='money' type='number' value='0.00'>").append("<input id='i3' class='money' type='number' value='0.00' step='.01'>");
$('.money').on('blur change', function(e) {
if ($(this).val() > 0) {
$(this).attr('step', '.01');
}
});
input[step*=".01"] {
border: 1px dashed red
}
<form id='form0'>
<input id='i0' class='money' type='number' value='0.00'>
<input id='i1' class='money' type='number' value='0.00'>
</form>
<form id='form1'></form>
<form id='form2'>
<input id='i4' class='money' type='number' value='0.00' step='.01'>
<input id='i5' class='money' type='number' value='0.00' step='.01'>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 11806
Use
$(".money-input").live('blur', function() {
var valTemp = $(this).val();
if ((valTemp.indexOf(".00") < 0) && (valTemp != "")) {
valTemp += ".00";
$(this).val(valTemp);
}
});
blur
is your 'lost-focus' event. With using live
it will attach this event to elements that exists now and in the future (since you are dynamically adding a form).
Upvotes: 1