简体   繁体   中英

Send textarea content to javascript function

Ok so I got a textarea and a link (which works as a button) and what I am trying to do is that when I click on the link, it sends the content from the textarea to a javascript function. Something like this...:

<textarea name="text" placeholder="Type your text here!"></textarea>
<a href="" onclick="myFunction(<!-- sends the value of the textarea that the user enters and then sends it to myFunction -->); return false;">Send!</a>

Just assign an id to your textarea, and use document.getElementById :

<textarea name="text" placeholder="Type your text here!" id="myTextarea"></textarea>
<a href="" onclick="myFunction(document.getElementById('myTextarea').value); return false;">Send!</a>

Alternatively, you could instead change your myFunction function, to make it define the value inside the function:

JS:

function myFunction() {
    var value = document.getElementById('myTextarea').value;
    //rest of the code
}

HTML:

<textarea name="text" placeholder="Type your text here!" id="myTextarea"></textarea>
<a href="" onclick="myFunction(); return false;">Send!</a>

And if you're using jQuery, which it does look like you do, you could change the document.getElementById('myTextarea').value to $('#myTextarea').val(); to get the following:

JS:

function myFunction() {
    var value = $('#myTextarea').val();
    //rest of the code
}

HTML:

<textarea name="text" placeholder="Type your text here!" id="myTextarea"></textarea>
<a href="" onclick="myFunction(); return false;">Send!</a>

you can do simply like this to achieve it, just call function and do all work in that function:

<a href="" onclick="myFunction();">Send</a>

Jquery code:

function myFunction()
{
    var text = $('textarea[name="text"]').val();

    // use text here

    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM