Ajax load the content from a variable with text string?

Let say I have a variable in javascript called var answer=“sample text”

And I have a button called “click this” with an id “done”

Now when someone click that button “click this”

It will fetch the value of variable answer and write this value into textarea,
and the id of this textarea is called right-answer.

How to do this in jquery ajax?
Can you guys show me the sample codes.

Sorry I’m no expert tin jquery ajax.
Also forgive me if my english is not good.

Thanks in advance.

Do I need jquery ajax for this?
Or this can be done in jquery only without ajax?

thanks in advance.

this has nothing to do with AJAX (which is for client-server-communication).

in fact, the required JavaScript is so simple, you don’t even need jQuery.

1 Like

I like jquery.
can you show me the codes in jquery please.

thanks

what have you tried so far?

So much that you’d waste bandwidth and memory only to do this with jQuery rather than plain JS? ;-) Anyway, here’s a vanilla JS solution:

var answer = 'sample text';
var button = document.getElementById('done');
var textarea = document.getElementById('right-answer');

button.addEventListener('click', function() {
    textarea.value = answer;
});

If you’re a bit familiar with JS and jQuery, rewriting it accordingly should be rather trivial. If not, I’d strongly suggest to learn those JS basics first, and then start exploring where it makes sense to use jQuery instead.

@m3g4p0p
thanks dude.
it works.

Here are the complete codes…

<html>
<head>
    <meta charset="UTF-8">
    <title>Title of the document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    
    <style type="text/css">

    </style>    
</head>

<body>
    <button id="done" type="button">Click Me!</button>
    <br><br>

    <textarea id="right-answer" rows="4" cols="50">

    </textarea>    
    

    <script>
        var answer = 'Testing...';
        var button = document.getElementById('done');
        var textarea = document.getElementById('right-answer');

        button.addEventListener('click', function() {
            textarea.value = answer;
        });        
    </script>
</body>
</html>

thanks again.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.