Adam
Adam

Reputation: 455

javascript alert value from a tag

I have on a page a tag links generated from a database with an id. What im trying to do is in an alert box display the text inside the a tag.

Ive tried to have a look to see if I can see a previous question, which I have come up with the following but all I get in the alert box is object HTMLCollection

I have the following code:

<a id="bet" onclick="addSlip();" class="btn btn-round" style="text-align: left;">'.$home->one.' <span>'.$home->two.'</span></a>

and...

function addSlip() {
    document.getElementById('bet').innerHTML=bet;
    alert(bet);
}

Thanks for any constructive answers

Upvotes: 0

Views: 1333

Answers (3)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

In your case alert will give you the HTML Object Collection only.

When you have an element with id, then you can access them anywhere in javascript

e.g. for the following HTML

<div id="bet">This is a div </div>

in JS

alert(bet); 

will give you the html object collection.

Solution for you is update your code

function addSlip() {
    document.getElementById('bet').innerHTML=bet;
    alert(bet);
}

to

function addSlip() {

    alert( document.getElementById('bet').innerHTML);
}

If there is some html elements also in the div you can update the function with

function addSlip() {

        alert(document.getElementById('bet').textContent);
    }

Upvotes: 0

cs04iz1
cs04iz1

Reputation: 1815

You should do the following

function addSlip() {
    var bet = document.getElementById('bet').textContent;
    alert(bet);
}

the rest as it is.

or using jquery

 function addSlip() {
        var bet = $("#bet").text()
        alert(bet);
    }

The main problem of your program was that the alerted variable had no value. (undefined) The way you wrote it if the variable bet had a value would change the innerHTML of the of the a tag to that value. Now to the using innerHTML or textContent part. As mentioned here in terms of performance the textContent is better

Upvotes: 2

Adam
Adam

Reputation: 44939

You need to reverse the variable assignment of bet:

function addSlip() {
    var bet = $("#bet").text();// or $("#bet").html() if you want the HTML alerted
    alert(bet);
}

Upvotes: 0

Related Questions