2013-01-17 144 views
0

我有以下的HTML代碼訪問HTML元素通過JavaScript

<input type="text" readonly name="Name" class="GadgetName" placeholder="Please Enter the Gadget Name" value="Potatoe Masher" /> 
<input type="text" readonly name="Description" class="GadgetDescription" placeholder="Please Enter the Gadget Description" value="You'll Never Stop Mashing !" /> 
<form action="SubmitComment" method="POST"> 
    <div class="Comment"> 
     <textarea rows="4" cols="200" name="Comment" class="GadgetComment" id="Comment2" placeholder="Write Comments Here"></textarea> 
     <input type="button" value="Submit Comment" class="CommentButton" onclick="AddComment()" /> 
    </div><br /> 
</form> 

我需要訪問的只讀文本框Name文本,並在Comment textarea的文本。

請注意,這些行位於for循環中,因此有多個組件具有相同的類名稱。

我設法使用此代碼

$(document).ready(function(){ 
    $(document).on("click", ".CommentButton", function(){ 
     text = $("textarea", $(this).parent()).val(); 
    }); 
}); 

我現在需要的是訪問在Name文本框中的文本來獲得在Comment textarea的價值。

+0

'$( 'GadgetName')VAL()' – Leeish

回答

1

下面是你是如何做到的。

$(document).ready(function() { 
    $('.CommentButton').click(function() { 
    console.log($(this).closest('form').parent().find('[name="Name"]').val()); 
    console.log($(this).parent().find('[name="Comment"]').val()); 
    }); 
}); 

您也可以在action中試用。

+0

我糾正多個項目的代碼。而且它不需要額外的標記,就像insomiac的答案一樣。 – uKolka

0

您可以通過兩種方式來實現:

  1. 從使用輸入的名字..

    $(document).ready(function() { 
    
    $(document).on("click", ".CommentButton", function() { 
        text = $("textarea", $(this).parent()).val(); 
        var name = $("input[name='Name']").val(); 
        var description = $("input[name='Description']").val(); 
        }); 
    }); 
    

OR

2使用的類名:

$(document).ready(function() { 

    $(document).on("click", ".CommentButton", function() { 
     text = $("textarea", $(this).parent()).val(); 
     var name = $(".GadgetName").val(); 
     var description = $(".GadgetDescription").val(); 
     }); 
    }); 

的jsfiddle:?http://jsfiddle.net/KZ9hx/1/

+0

嗨,很遺憾,它沒有工作, 第一個解決方案是什麼時候適用於多個產品;當按下相應的按鈕時文本會改變,但名稱和說明仍會顯示第一項的內容。 第二個解決方案也只顯示第一個項目的描述和名稱 – Andrew

+0

你可以發佈你的完整的HTML,這樣我可以幫你嗎? – insomiac

+0

檢查我更新的答案並檢查jsfiddle網址。我想我解決了你的問題。 – insomiac