2013-01-17 97 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