0

I am prepending inputs on a dom element div as shown below:

<div class="parentDiv">
  <div onClick="addInputs()">Add inputs</div>
  <div id="inputsContainer"></div>
</div>
<!-- hardcoded inputs -->
<input type="text">
function addInputs() {
  $("#inputsContainer").prepend("<input type='text'>");
}

$("input").focusin(function(){
  $(this).css("background-color", "#FFFFCC");
});

This focusin works on hardcoded inputs, but does not trigger on prepended inputs. Let me know where I am going wrong.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • You need to use a delegated event handler as you're appending new `input` elements after the DOM has loaded. Also note that the use of `onclick` is very outdated. I'd strongly suggest using an unobtrusive event handler instead - exactly as you are for the `focusin` event handler – Rory McCrossan Jun 08 '18 at 10:21
  • @Rory McCrossan, thanks buddy. Found the answer there. – Uzair Khan Jun 08 '18 at 10:25
  • 1
    No problem, glad you got it working – Rory McCrossan Jun 08 '18 at 10:26
  • 1
    One last thought - you can do the style change on focus using CSS alone without need for JS: `input:focus { background-color: #FFC; }` – Rory McCrossan Jun 08 '18 at 10:27
  • @Rory, thing is I need to do some other things on focus-in and focus-out, I wrote the above template just as an example. But thanks. – Uzair Khan Jun 08 '18 at 10:34
  • Just try this :
    Add inputs
    – Sanjay Kumar Jun 08 '18 at 10:36
  • https://www.w3schools.com/code/tryit.asp?filename=FS4YFNZ1A8LV – Sanjay Kumar Jun 08 '18 at 10:38

0 Answers0