从Javascript访问HTML元素

时间:2013-01-17 23:30:21

标签: javascript html jsp

我有以下HTML代码

<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循环中,因此有多个组件具有相同的类名。

我设法使用此代码

获取Comment textarea中的值
$(document).ready(function(){
    $(document).on("click", ".CommentButton", function(){
        text = $("textarea", $(this).parent()).val();
    });
});

我现在需要访问Name文本框中的文字。

2 个答案:

答案 0 :(得分: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中试用。

答案 1 :(得分: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();
       });
    });
    
  2. 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/