javascript - Using Jquery to write html of Div based off of variable -
i'm in process of making simple web based calculator. i'm having trouble assigning value of buttons "screen" area want show value of number pressed. can value javascript variable, when attempt write screen area coming undefined.
here code:
$(".numbers").click(function(){ currentvalue = ($(this).val()); $("#screen").html(function(){ return "<p> " + currentvalue.tostring() + "</p>"; }) });
the problem seems code getting run twice, when have set return (if use return "test" works perfectly).
based on code have provided, believe need:
$(".numbers").click(function() { currentvalue = $(this).val(); $("#screen").html("<p> " + currentvalue + "</p>") });
i believe instead of using .html()
, should using append()
or use input box screen , use .val()
. how have it, using .html
, overwriting screen every time number pressed. can still use .html()
have concatenate orignal screen value new button number:
$('#screen').html($('#screen').html() + currentvalue);
but it's better use .append()
:
$('#screen').append(currentvalue);
have @ fiddle uses input box:
<input type="text" id="screen"></input> <button class="numbers" value="1">1</button> <button class="numbers" value="2">2</button> <button class="numbers" value="3">3</button> $(".numbers").on('click', function() { var $s = $('#screen'); $s.val($s.val() + $(this).val()) });
each time number pressed, adds end of string of numbers, instead of overwriting everything.
Comments
Post a Comment