2012-06-13 79 views
0
<div id="post"> 
    <form name="postComment" id="commentPost6" action="javascript:void(0);" method="post" 
    target="_top" onsubmit="return commentPost(6)"> 
    <textarea name="comment" id="comment6" class="commentText" 
     cols="10" rows="3" accesskey="1"> 
    </textarea><br> 
    <input type="submit" name="submit" id="commentpost" value="Submit" accesskey="2"> 
    </form> 
</div> 

這是我 div標籤,我有相同的id =「POST」 多個DIV標籤, 形式和領域是動態生成的,並都形式textarea的的ID都是唯一的,這樣在回收這些值時沒有問題,點擊提交後,我打電話給評論郵政方法。在jQuery中檢索動態生成的textarea的值?

function commentPost(postId) 
{ 
    alert("Inside commentpost"); 
    //how to retrive/access value of textarea here 

} 

如何獲得textarea的價值? ,以防萬一

是的,我知道這是不是有效的HTML有多個元素具有相同的ID。

+1

是的,你知道這是不是有效。是的,你仍然不明白爲什麼大家都說你應該寫有效的HTML。改用類。 – kapa

+0

沒關係,bažmegakapa如果我使用類,那麼如何將我檢索值,因爲我試圖用類,並沒有爲我工作了好,所以告訴我,如果我錯了,究竟我在哪裏 –

回答

4
$('#comment'+postId).val(); 

爲什麼不簡單地使用類而不是id? (POST)

1
function commentPost(postId) 
{ 
    alert("Inside commentpost"); 
    aler($("#commentPost"+postId).find('textarea').val()); 

} 

這會給你的textarea的價值

1

修訂的HTMLpost現在是A級,來自action刪除javascript:):

<div class="post"> 
    <form name="postComment" id="commentPost6" action="" method="post" 
    target="_top" onsubmit="return commentPost(this)"> 
    <textarea name="comment" id="comment6" class="commentText" 
     cols="10" rows="3" accesskey="1"> 
    </textarea><br> 
    <input type="submit" name="submit" id="commentpost" value="Submit" accesskey="2"> 
    </form> 
</div> 

的Javascript:

function commentPost(form) 
{ 
    var textAreaValue = $(form).find('.commentText').val(); 
    console.log(textAreaValue); 
} 

更妙的是,你應該開始寫先進的事件處理程序,而不是行內的人(onsubmit=""和朋友)。 jQuery爲此提供great methods

$('.post form').submit(function (e) { 
    var textAreaValue = $(this).find('.commentText').val(); 
    console.log(textAreaValue); 

    e.preventDefault(); //to prevent default event - which is form submission 
}); 

內聯事件處理程序適用於快速測試,但它們很快就會導致無法維護的混亂HTML源代碼。你應該遵循Separation of Concerns的規則。如果你通過匹配在表格命名標準像上面你有6

function commentPost(postId) { 
     alert("Inside commentpost"); 
     // One way. 
     var $testAreaValue = $('textarea.commentText#comment' + postId).val(); 
     alert($testAreaValue); 
     // second way. 
     $testAreaValue = $('#comment' + postId).val(); 
     alert($testAreaValue); 
} 

希望它有助於帖子ID

取決於:

+0

okayyy,THT的有趣 感謝:) –

0

試試這個。

相關問題