Reputation: 495
I have 3 buttons and an input, i want when i click on one of those buttons the value or source of this input to change according to the button, like for example when i click on the first button it passes apple, when i click on button two it passes orange, etc.. How can i do that? here is what i have tried so far:
$(document).ready(function() {
$('button').click( function() {
$('input').val('value');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Button 1</button>
<button type="button">Button 2</button>
<button type="button">Button 3</button>
<input type="text" value="">
Upvotes: 1
Views: 60
Reputation: 1
you can do this even with simple javascript....
function insertValue(btn) {
document.getElementById("input").value = btn;
}
<button onClick='insertValue("Orange")'>Orange</button>
<button onClick='insertValue("banana")'>banana</button>
<button onClick='insertValue("Apple")'>Apple</button>
<input type=text id="input" />
Upvotes: 0
Reputation: 5516
You could even use id
s on the buttons. However, in this example I think it's more semantic using a data-attribute
on each button like so:
$(document).ready(function() {
$('button').click(function() {
$('input').val($(this).data('attribute'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-attribute='apple'>Button 1</button>
<button type="button" data-attribute='orange'>Button 2</button>
<button type="button" data-attribute='banana'>Button 3</button>
<input type="text" value="">
Upvotes: 4
Reputation: 797
Add custom attribute button element ans pass it your click event HTML:
<button type="button" data-fruit="apple">Button 1</button>
<button type="button" data-fruit="banana">Button 2</button>
<button type="button" data-fruit="orange">Button 3</button>
JS:
$(document).ready(function() {
$('button').click( function() {
var fruit = $(this).attr('data-fruit');
$('input').val(fruit);
});
});
Upvotes: 2