0

I want to use javascript in my custom Joomla content plugin, but I can't get my custom text when type text in my input by using getElementById.

My code is:

<?php
    $output = '
        <input type="text" id="name" value="default" />
        <button onclick="myAlert();" >test code</button>
        <script>
            var myText = document.getElementById("name").value;
            function myAlert(){
                alert(myText);
            } 
        </script>
        ';
?>

When I click the button only alert default value and not my custom name.

How can I do this?

3
  • check console for any errors
    – Nick
    Commented Dec 29, 2014 at 10:52
  • I found my problem it's simple. I must placed var myText inside the function. now it's work
    – saber
    Commented Dec 29, 2014 at 11:06
  • 1
    Please add an answer with your working code, it might help other users later.
    – johanpw
    Commented Dec 29, 2014 at 12:31

2 Answers 2

2

Check JDocument functions to add scripts to the page output:

2

I found my problem it's simple. I must placed var myText inside the function. now it's work this code work:

<?php
$output = '
    <input type="text" id="name" value="default" />
    <button onclick="myAlert();" >test code</button>
    <script>
        function myAlert(){
            var myText = document.getElementById("name").value;
            alert(myText);
        } 
    </script>
    ';
?>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.