2014-05-25 98 views
0

好吧,所以我得到了一個textarea和一個鏈接(它作爲一個按鈕),我想要做的是,當我點擊鏈接時,它將內容從textarea發送到javascript函數。 這樣的事情...:發送textarea內容到javascript函數

<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> 

回答

4

只是分配一個id你的文字區域,並使用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> 

或者,你可以代替更改myFunction功能,使它定義函數內的值:

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> 

如果你正在使用jQuery,它看起來像你這樣做,你可以改變document.getElementById('myTextarea').value$('#myTextarea').val();得到如下:

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> 
+1

謝謝!添加一個id和document.getelementbyid就像我想要的一樣工作! – user3673837

1

你可以做簡單地這樣來實現它,只需調用函數和做所有的工作在那個函數:

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

jQuery代碼:

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

    // use text here 

    return false; 
}