Reputation: 123
is there a simple way to add a string to a input value.
something like my snippet or maybe something like :
$("#cost").change(function () {
$(this).val(function (e) {
return e.value += ".00";
});
});
excuse my green attempt, what do you except from a newbie ;)
thanks
$("#cost").change(function () {
var myCostVal = $("#cost").val();
return myCostVal += ".00";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Cost</label>
<input type="text" name="cost" id="cost" class="form-control" />
Upvotes: 1
Views: 26
Reputation: 337600
To set the value of an input you need to set the val()
, not return
a value from the event handler. Also note that if your goal is to display the value to 2DP, as it seems to be from the context, then you can parse the value to a float and use toFixed()
. Try this:
$("#cost").on('change', function() {
$(this).val((i, v) => parseFloat(v).toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Cost</label>
<input type="text" name="cost" id="cost" class="form-control" />
Upvotes: 1