Reputation: 21
Im Sorry If this is a easy question, i am new to Scripting and html and JQuery. I am trying to make it so when the 1 button is pressed that it will show the value in the box. I acheived it earlier with Get Element By Id but i am now trying it with Jquery and i am confused why my following code wont work. Thanks for any help!
<html>
<head>
<title>Page Title</title>
</head>
<script>
$(document).ready(function(){
$('#button1').click(function(){
var number1 = "1";
$('#output').html(number1);
});
});
</script>
<body>
<input type="text" id="output">
<input type="button" name="one" value = "1" id="button1">
</body>
</html>
Upvotes: 0
Views: 6257
Reputation: 21
At first, I think you forgot to call jQuery. So add this on the header area--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Second, chenge the
$('#output').html(number1);
to
$('#output').val(number1); // use val because input tags contain value not html
And also if you want the value will come from the clicked button then you can use dynamically
$(this).val(); // this will handle the selector which is clicked by you and its value
and you can put this inside a variable as
var number1 = $(this).val();
Upvotes: 0
Reputation: 2073
to get button value with jquery use $("#button1").attr("value")
or $("#button1").val()
In your case to set value of input text use $('#output').val($(this).attr("value"))
The final code shoul be
<html>
<head>
<title>Page Title</title>
</head>
<script>
$(document).ready(function(){
$('#button1').click(function(){
$('#output').val($(this).val());
});
});
</script>
<body>
<input type="text" id="output">
<input type="button" name="one" value = "1" id="button1">
</body>
</html>
Upvotes: 1
Reputation: 5494
$(document).ready(function(){
$('#button1').click(function(){
alert($('#output').val());
});
});
I guess you kind of mixed up your mind. #output
is the input in your code, so thats where you'd want to read the value from. If you want to print the value to another element you would have to append one and change the ids like so:
<input type="text" id="input">
<button id="button">Submit</button>
<span id="output"></span>
<script>
$(document).ready(function(){
$('#button').click(function(){
// Always use .text() if you dont need html output.
$('#output').text($('#input').val());
});
});
</script>
Edit: it turns out I kinda mixed up my own mind ;) I see you want to output the value of the button that is clicked, simply do:
$(document).ready(function(){
$('#button1').click(function(e){
// Either use $(this) or $(e.target).
$('#output').text($(this).val());
});
});
You might want to read this article on this
and $(this)
in jQuery.
Upvotes: 0
Reputation: 5948
$(document).ready(function(){
$('#button1').click(function(){
var value = $(this).val();
$('#output').val(value);
});
});
See working example here: http://jsfiddle.net/jqnynLbm/
Upvotes: 0