Roman Nrokov Roman Nrokov - 1 month ago 7
Javascript Question

Increase input value by Math Random function

I have some inputs, and when it focused, value increases by 10 times, I can see this value in console, but I cant push into certain input value. Any ideas?

for (var i = 0; i < 3; i++) {
var random = Math.floor((Math.random() * 100) + 1);
$('body').append("<input type='text' value='" + random + "'>")
$('input').focus(function() {
console.log(+$(this).val() * 10)
})
}

Answer

Declare the focus event outside the loop and set the value of the input with .val()

// Get
$('#inputId').val()

// Set
$('#inputId').val( 10 )

.val() documentation

for (var i = 0; i < 3; i++) { 
    var random = Math.floor((Math.random() * 100) + 1); 
    $('body').append("<input type='text' value='" + random + "'>") 
}
$('input').focus(function() { 
  $(this).val( parseInt($(this).val()) * 10 );
}) 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments