JQuery get the title of a button

JavascriptJquery

Javascript Problem Overview


I have a button:

<button type="button" onclick="toggleColor('white');" >White</button>

Which makes this:

enter image description here

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

You can get it by using .text(),

$('button').text();

Please read here to know more about it.

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeekorView Question on Stackoverflow
Solution 1 - JavascriptRajaprabhu AravindasamyView Answer on Stackoverflow
Solution 2 - JavascriptSatish SharmaView Answer on Stackoverflow
Solution 3 - JavascriptMusicLovingIndianGirlView Answer on Stackoverflow
Solution 4 - JavascriptNoctisView Answer on Stackoverflow
Solution 5 - Javascriptuser2930100View Answer on Stackoverflow
Solution 6 - JavascriptShivamView Answer on Stackoverflow
Solution 7 - JavascriptMorris SView Answer on Stackoverflow
Solution 8 - JavascriptpratView Answer on Stackoverflow