JQuery get the title of a button
JavascriptJqueryJavascript Problem Overview
I have a button:
<button type="button" onclick="toggleColor('white');" >White</button>
Which makes this:
Is there any way to get what is written on the button using jQuery. For example this button would return White
because its in-between the 2 button tags.
Javascript Solutions
Solution 1 - Javascript
Solution 2 - Javascript
add id to your button like this
<button type="button" onclick="toggleColor('white');" id="your_button_id" >White</button>
now you can use JS like this
var button_text = document.getElementById('your_button_id').innerHTML;
and also you can use JQUERY like this
var button_text = $('#your_button_id').text();
Solution 3 - Javascript
Try
$("button").click(function(){
var title=$(this).attr("value");
alert(title);
});
Solution 4 - Javascript
You can do this with Vanilla JS, after you've added an ID so you can fetch the element.
Assuming:
<button type="button" onclick="toggleColor('white');" id='myButton'>White</button>
You can do in JavaScript:
var someVar = document.getElementById('myButton').innerHTML; // -> White
var anotherVar = document.getElementById('myButton').textContent; // -> White
Both will hold "White"
Solution 5 - Javascript
give the button an ID
<button id="btnTest" type="button" onclick="toggleColor('white');" >White</button>
JQuery:
alert($("#btnTest").text());
Solution 6 - Javascript
Just provide one id to button and use it with JQuery
<button id=btn type="button" onclick="toggleColor('white');" >White</button>
then use jquery like this
$("#btn").val();
it will work for your condition.
Solution 7 - Javascript
Try this event.target
$("button").click(function(event){
var text=$(event.target).attr("value")
alert(text);
});
Solution 8 - Javascript
This worked for me on chrome.
$("#your-button-id").val();