Reputation: 518
I have an icon that when clicked will increase the value of a number input.
I initially wrote it as:
$('.icon-chevron-up').click(function(){
var input = $(this).next();
var value = eval(input.val());
input.val((value+1).toString());
$(this).next.val(value+1);
});
I then rewrote it as:
$('.icon-chevron-up').click(function(){
$(this).next().val((eval($(this).next().val()) + 1).toString());
});
Is there a preferred way of doing this? And if so, why?
Upvotes: 0
Views: 61
Reputation: 2189
What do you mean by input? should it be text input or just a html tag?
<button class="icon-chevron-up">Increase</button>
<div id="numinput">12</div>
var input = $('#numinput').html();
$('.icon-chevron-up').click(function(){
input++;
$('#numinput').html(input);
});
Upvotes: 0
Reputation: 94101
None of those would be the best for efficiency. eval
is not needed and if you want performance you should cache your selectors. There are a couple ways you could make it more efficient but I would do it like this:
$('.icon-chevron-up').click(function() {
var $this = $(this),
val = $this.next().val();
$this.next().val( ++val + '' );
});
++
casts val
to a number and adds 1
. + ''
casts the previous number to a string.
If you want something less terse (more readable I guess):
$this.next().val( (parseInt( val,10 ) + 1).toString() );
Upvotes: 1