Retrieve data from selected text input among various text inputs with same name & id upon hitting Enter

StackOverflow https://stackoverflow.com/questions/19390051

  •  30-06-2022
  •  | 
  •  

سؤال

I have several text input dynamically created with same id and same name. I want to fetch the data being typed in a particular text input whenever a user presses 'Enter' key in that text input.

For eg., I have

<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />

Each input has been created dynamically on some event. Now let say, there are 4 text inputs on the screen. User can type anything in them. I want that whenever a user presses the 'Enter' key in any text input, the data in that particulat text-input should be alerted.

I have used:

$(document).on('keypress','#fetchChatMsg', function(e) {
    if(e.which==13)
        alert($('#fetchChatMsg').val());
});

But it's really ambiguous. Please sort this out, maybe classes can handle this ?

هل كانت مفيدة؟

المحلول

Try this, without duplicate ID's but class instead.

jQuery

$(document).on('keypress','.fetchChatMsg', function(e) {
    if(e.which==13)
        alert(this.value);
});

HTML

<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />

Demo here

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top