简体   繁体   English

单击按钮时如何获得输入值

[英]How I get input value when button is click

I have same html code but id is different for button now I want to get value of input field that is nearest to button which is click. 我有相同的html代码,但按钮的id不同,现在我想获取最接近单击按钮的输入字段的值。

Here is my html code: 这是我的html代码:

<input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="Write your message here..." ng-model="messageToSend">
    <span class="input-group-btn">
    <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="38">Send</button>
    </span>

<input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="Write your message here..." ng-model="messageToSend">
    <span class="input-group-btn">
    <button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="39">Send</button>
    </span>

Here is my jQuery code: 这是我的jQuery代码:

$(document).on('click', '.btn_chat', function (e) {
    alert("Button id: "+$(this).val());
    alert($(this).closest('input .message').val());
});

It will gives button value but input value is undefined 它将提供按钮值,但输入值未定义

Firstly, you should remove the duplicate id attributes and use classes to group your elements instead. 首先,您应该删除重复的id属性,并使用类对元素进行分组。

You can then use closest() to traverse the DOM to the nearest parent span and then use prev() to get the input . 然后,您可以使用closest()将DOM遍历到最近的父span ,然后使用prev()来获取input Try this: 尝试这个:

$(document).on('click', '.btn_chat', function (e) {
    var $input = $(this).closest('span').prev('input.message');
    alert($input.val());
});

Note the removal of the space between input and .message in the selector as we are looking for both of those properties on a single element. 请注意,当我们在单个元素上查找这两个属性时,请注意选择器中input.message之间的空格已删除。

there should be difference between ID and CLASS and you are referring the class .btn-chat which is in both elements. IDCLASS之间应该有区别,并且您引用的是两个元素中的.btn-chat类。 Remember the ID should be unique so that it will be identified by your handler. 请记住, ID应该是唯一的,以便您的处理程序可以识别它。

you have repeated your ID's 您已经重复了您的身份证

but a simple jquery can return you answer: 但是一个简单的jQuery可以返回答案:

$(".btn_chat").click(function(){
    alert($(this).parents('.input-group').find('input').val());
});

Working Fiddle 工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM