Reputation: 15
I want to change the text of a element by clicking on another button. So if I click on a button with text the desired element will get the same text.
This is for a fan-made game menu for Halo 5 Guardians - PC version. It will be tool for players to use to their advantage.
<div class="left_menu" id=left_menu>
<button id="option1" class="left_menu-option">option 1</button>
<button id="option2" class="left_menu-option">option 2</button>
<button id="option3" class="left_menu-option">option 3</button>
</div>
<div>
<button class="left_menu-open" id="left_menu_open">
<span class="button-text">text goes here</span>
</button>
</div>
I've tried using dropdowns and select menus, but the main requirement is that the button needing text changed can be in a separate div from the options.
Upvotes: 0
Views: 34
Reputation: 23379
You would use event listeners. jQuery makes it easy (since you tagged jQuery).
$(document).on('click', '#left_menu button', function(){
$("#left_menu_open .button-text").text(this.innerHTML);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left_menu" id=left_menu>
<button id="option1" class="left_menu-option">option 1</button>
<button id="option2" class="left_menu-option">option 2</button>
<button id="option3" class="left_menu-option">option 3</button>
</div>
<div>
<button class="left_menu-open" id="left_menu_open">
<span class="button-text">text goes here</span>
</button>
</div>
Upvotes: 0
Reputation: 3293
You should use the .text()
function, this lets you set the text of the span
within your button. It will also let you get the text from the clicked button.
N.B. you're naming convention was a little odd so I've changed
.left_menu-option
to.left_menu_option
so that it is consistent with the convention you've used for the button (#left_menu_open
).
// Add click event to all buttons with the class .left_menu-option
$(".left_menu_option").click( function() {
// Set the text of the button
$("#left_menu_open .button-text").text($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left_menu" id=left_menu>
<button id="option1" class="left_menu_option">option 1</button>
<button id="option2" class="left_menu_option">option 2</button>
<button id="option3" class="left_menu_option">option 3</button>
</div>
<div>
<button class="left_menu-open" id="left_menu_open">
<span class="button-text">text goes here</span>
</button>
</div>
Upvotes: 1