0

I have this code:

$('#output').html("<strong>id:</strong>"+id);

then

<div id="output">this element will be accessed by jquery and this text replaced</div>

The above works fine but what I need is for the output to go into an alert so....

<a href="#" onclick="alert('OUTPUT GOES HERE')">Alert Me</a>  <- See here

How can this be done?

6
  • FYI <b> will be deprecated Commented Nov 19, 2012 at 15:52
  • 3
    @banzsh - can you document that claim ? Commented Nov 19, 2012 at 15:54
  • Do you mean you want the html to be visible in the alert Commented Nov 19, 2012 at 15:55
  • @banzsh: That is incorrect. See this answer to Will the <b> and <i> tags ever become deprecated? Commented Nov 19, 2012 at 15:56
  • I may be wrong but quite sure I read it on w3c spec that cannot find now. However I'd like styling to be exclusively in stylesheet than html and stylesheet :) Cheers Commented Nov 19, 2012 at 16:09

3 Answers 3

1

Give the anchor some type of id or attribute that can be used to look it up:

<a href="#" id="alertOutput">Alert Me</a>

Then bind to its click event to alert the text content of the #output element:

$("#alertOutput").on("click", function(e){
    e.preventDefault();
    alert( $("#output").text() );
});

The e.preventDefault() portion will prevent the page from jumping back to the top of the document when the anchor is clicked.

Sign up to request clarification or add additional context in comments.

2 Comments

Ha! We had the same answer :P
@Chad Genius minds think alike, and it was a fairly basic question :)
1

Not sure I exactly understand what you are asking, bind the click event instead of the onclick attribute.

HTML:

<a href="#" id="alertAnchor">Alert Me</a>

JavaScript:

$('#alertAnchor').on('click', function(e) {
    e.preventDefault();
    alert($('#output').text());
});

Hope this helps, if you clarify what you are looking for I can edit.

Comments

1

or if you are lazy and want a quick fix:

<a href="#" onclick="e.preventDefault(); alert($('#output').html())">Alert Me</a>  <- See here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.