Search code examples
javascriptbuttononclickinnerhtml

Change button text when onclick


I've this line of code

<?php 
$STRING .= '<a href="#" onclick="changeText(this)" class="btn btn-info btn-lg"></a>';
?>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>

which works fine and the button text changes to Oooops

I want the button text to change to the output of

 $data = get_user_meta( $authorID, 'cellno', true);

I change the value of

id.innerHTML = "Ooops!";

to

id.innerHTML = "$data = get_user_meta( $authorID, 'cellno', true)";

or

id.innerHTML = "$data";

but it doesn't work :(, what am I doing wrong?

EDIT: this is the where I took the function of data

 $data = get_user_meta( $authorID, 'cellno', true);
        if(strlen($data) > 0){ 
        echo "<span><i class='fa fa-phone'></i> <a href='phone:".$data."' rel='nofollow' target='_blank'>Mobile</a> </span>"; 
        }

does it change a thing?

the $data is from another file :D


Solution

  • This is something you shouldn't actually do, because you have inline javascript and a <script> tag being outputted by php. You should have your javascript in separate files.

    But here's how to fix what you're trying to do:

    <?php 
    $STRING .= '<a href="#" onclick="changeText(this)" class="btn btn-info btn-lg"></a>';
    $data = get_user_meta( $authorID, 'cellno', true);
    ?>
    
    <script>
    function changeText(id) {
    id.innerHTML = <?php echo $data;?>;
    }
    </script>