Resize individual dynamically created text input on keyup which has several siblings with same class

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

  •  30-06-2022
  •  | 
  •  

Question

Any help would be appreciated on this please. I'm trying to resize a dynamically created text input on keyup. I can get this to work on a basic level but I'm having trouble resizing individual inputs which have the same class — i.e Instead of just one individual input field resizing, all text inputs with class ".question" are resizing.

Here is my code:

function resizeInput(theInputField) {
  var getInputWidth = $(theInputField).width();
  if(getInputWidth < 400){
    $(theInputField).attr('size', $(theInputField).val().length);
  }
}

$('#question-list').on('keyup', '.question', function(){
  resizeInput('.question');
});

$('#question-list') --> This is a ul element.

$('.question') --> This is a dynamically created input[type="text"] in the above ul.

Était-ce utile?

La solution

In your event handler, this is the element which triggered the event. You could do something like this:

function resizeInput($theInputField) {      
  var inputWidth = $theInputField.width();
  if(inputWidth < 400){
    $theInputField.attr('size', $theInputField.val().length);
  }
}

$('#question-list').on('keyup', '.question', function(){
  resizeInput($(this));
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top