How to pull the text in a paragraph element?

im trying to assign the text in a paragraph to a var in JavaScript and then change it with a button, but it wont seem to do it. Heres whats in my index.php file:

<button type="button">click</button>
<p class="result" id="number">default</p>
<button onclick="showPtag()">Show</button>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            url: 'math.php',
            success: function(data) {
                $('#number').html(data);
            }
        });
     });
});

var par = document.getElementById('number').innerHTML;
function showPtag()
{
   alert(par);
}
</script>

and this is in math.php:

<?php 
 $var = 10;
 $var2 = 10;
 echo $var * $var2;
?>

what it does is theres a paragraph tag that says 'default' on the page load, and when you click a button it changes the text to say what ever the math is, in this case it would change to 100, and when you click the Show button it brings an alert. Im trying to get the alert to say 100 when the text says 100, but no matter what it always says 'default' even if the text is 100. Are there any possible fixes/work-arounds for this?

Answers


In your case

var par = document.getElementById('number').innerHTML;

is read at page load, so it will always be "default" no matter what. You will need to put this in your function to have the actual value alerted:

function showPtag(){
    // assign the value that your result has now
    var par = document.getElementById('number').innerHTML;
    alert(par);
}

change

var par = document.getElementById('number').innerHTML;
function showPtag()
{
    alert(par);
}

to

function showPtag(){
    alert($('#number').html());
}

Need Your Help

Get all email addresses of user using Google API

email gmail google-api google-api-client

For my own gmail account, I have multiple email addresses associated with it. For example, I have an email address from my university that is associated with my gmail, and I can send emails from my