I have this code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form name="myform">
Your number:
<input type="number" name="inputbox" id='textBox' value="" />
<input type="button" name="button" value="Click me!" />
<div class='box1' style='border:1px solid #333333;margin-top:15px;width:33.33%;height:50%;padding-left:15px;padding-right:15px;'>
<h3>
0
</h3>
<p>
Valor
</p>
</div>
</form>
<script>
$(function() {
$('.member').click(function() {
var answer = $("#textBox").val();
if (answer <= 20) {
$('.box1').css('background-color', 'red').find('h3').html(answer);
} else if (answer <= 50) {
$('.box1').css('background-color', 'orange').find('h3').html(answer);
} else {
$('.box1').css('background-color', 'steelblue').find('h3').html(answer);
}
});
});
</script>
It works. But, I'd like to not need to click for the value to appear. That is, that it would be updated inside the div when I typed the number in the "Your number" field.
For example, if I type 75, the value appears automatically, without having to press any button.
I tried remove:
$('.member').click(function() {...})
But don't work.
CodePudding user response:
You need to add on input
to the text box like,
$('#textBox').on("input", function(){ ... });
Forked working example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form name="myform">
Your number:
<input type="number" name="inputbox" id='textBox' value="" />
<input type="button" name="button" value="Click me!" />
<div class='box1' style='border:1px solid #333333;margin-top:15px;width:33.33%;height:50%;padding-left:15px;padding-right:15px;'>
<h3>
0
</h3>
<p>
Valor
</p>
</div>
</form>
<script>
$(function() {
$('#textBox').on("input", function() {
var answer = $("#textBox").val();
if (answer <= 20) {
$('.box1').css('background-color', 'red').find('h3').html(answer);
} else if (answer <= 50) {
$('.box1').css('background-color', 'orange').find('h3').html(answer);
} else {
$('.box1').css('background-color', 'steelblue').find('h3').html(answer);
}
});
});
</script>