dongzhouzhang8696
2015-05-12 06:22
浏览 9

试图从任何点击的表单或按钮获取消息的价值?

The variable message in the script is returning undefined while the variable name is true... I want to actually the input text by from the name of the button clicked

<script type="text/javascript">
$(function() {
    $(".submitcc").click(function() {
        var name = $(this).attr("name");
        var message = $("#" + name).val();
        return false;
    });
});
</script>

This is the form that is calling the script above...

<form method="post" action="">
    <input type="text" name="message" id="submitcc_2_2" />
    <button class="submitcc"name="submitcc_2_2">Send</button>
</form>

<form method="post" action="">
    <input type="text" name="message" id="submitcc_5_2" />
    <button class="submitcc"name="submitcc_5_2">Send</button>
</form>

is there something wrong?

图片转代码服务由CSDN问答提供 功能建议

当变量名为true时,脚本中的变量消息返回undefined ...我想实际输入 单击按钮名称中的文本

 &lt; script type =“text / javascript”&gt; 
 $(function(){
 $(“。。submitcc  “).click(function(){
 var name = $(this).attr(”name“); 
 var message = $(”#“+ name).val(); 
 return false; \  n}); 
}); 
&lt; / script&gt; 
   
 
 

这是调用上面脚本的表单... \ n

 &lt; form method =“post”action =“”&gt; 
&lt; input type =“text”name =“message”id =“submitcc_2_2”/&gt; 
&lt;  button class =“submitcc”name =“submitcc_2_2”&gt;发送&lt; / button&gt; 
&lt; / form&gt; 
 
&lt; form method =“post”action =“”&gt; 
&lt; input type =“text  “name =”message“id =”submitcc_5_2“/&gt; 
&lt; button class =”submitcc“name =”submitcc_5_2“&gt;发送&lt; / button&gt; 
&lt; / form&gt; 
   
 
 

有什么不对吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doucan8246326 2015-05-12 06:24
    已采纳

    The scope of message is in the function only.

    You have to use $('input[name="message"]') to get message from input.

    You can use

    var message = $('input[name="message"]').val();
    

    Where you need the message

    If you have multiple forms on the page:

    $(function () {
        var message = '';
    
        $(document).on('click', ".submitcc", function () {
            message = $("#" + $(this).attr("name")).val();
    
            return false;
        });
    
        // You can use message here
    });
    
    点赞 打赏 评论
  • douxi4114 2015-05-12 06:28

    Your code is working check this fiddle

    Although you can directly access element using following way

    var message = $('#submitcc_2_2').val();
    
    点赞 打赏 评论

相关推荐 更多相似问题