Reputation: 73
I'm trying to create a function so that when one of my buttons is pressed the value of the text input changes to the value of the button pressed.
<div id="viewer">
<h1>
<input type="text" id="Screen" maxlength="8" value="0"/>
</h1>
<h2>
<button type="button" value="1" id="1">1</button>
<button type="button" value="2" id="2">2</button>
</h2>
</div>
This is the function I am trying to use but am going wrong somewhere:
$(document).ready(function(){
$("button").click(function(){
var $val = $("#Display").val();
alert($val);
onclick="sevenClick()";
});
});
});
Upvotes: 1
Views: 53
Reputation: 299
Simply get the value of button and set it to the input box
$(document).ready(function() {
$("button").click(function() {
var butVal = $(this).val(); //get current button value here
$("#Screen").text(butVal); // set button value to the textbox
});
});
Upvotes: 0
Reputation: 129
$(document).ready(function() {
$('button').click(function() {
var test = $(this).attr('value');
$('#Screen').val(test);
});
});
Upvotes: 1
Reputation: 38252
Use this
to keep the actual button value:
$(document).ready(function() {
$("button").click(function() {
var $val = $(this).val();
//alert($val);
$('#Screen').val($val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="viewer">
<h1>
<input type="text" id="Screen" maxlength="8" value="0"/>
</h1>
<h2>
<button type="button" value="1" id="1">1</button>
<button type="button" value="2" id="2">2</button>
</h2>
</div>
Upvotes: 0
Reputation: 21005
I think you changed an ID and need to change a few other things
$(document).ready(function() {
$("button").click(function() {
var val = $(this).val()
$("#Screen").val(val);
alert(val);
onclick = "sevenClick()";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="viewer">
<h1>
<input type="text" id="Screen" maxlength="8" value="0"/>
</h1>
<h2>
<button type="button" value="1" id="1">1</button>
<button type="button" value="2" id="2">2</button>
</h2>
</div>
Upvotes: 0