简体   繁体   中英

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.

Here is my html code:

<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:

$(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.

You can then use closest() to traverse the DOM to the nearest parent span and then use prev() to get the 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.

there should be difference between ID and CLASS and you are referring the class .btn-chat which is in both elements. Remember the ID should be unique so that it will be identified by your handler.

you have repeated your ID's

but a simple jquery can return you answer:

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

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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