0

I used the append method in jQuery to generate some HTML input boxes; now I want to make some effects on those input elements using jQuery but I can't. This is a little example of what I wanna do.

 <style type="text/css"></style>
 <style>
 .focus
 {
   background-color: green;
 }
 </style>
 <script src="alu_afric/Java/java.js"></script>
 <script>
$(document).ready(function() {
  $("button").click(function() {
    $("#newHTML").append('<input type="text" placeholder="some text .."/>');
  });
  $("input").focus(function() {
    $(this).addClass("focus");
  });
});
 </script>
 <button>Click</button>
<body>
<div id="newHTML"></div>
</body>
RamenChef
  • 5,557
  • 11
  • 31
  • 43
M-Amr Moussa
  • 107
  • 1
  • 2
  • 9
  • You could just have a `input:focus { background-color: green; }` in the css, then you have no need to worry about jquery – Bassie Sep 17 '16 at 14:34

3 Answers3

0

The event listener should be

$( document ).on( 'focus', 'input[type=text]', function() {

Instead of

$("input").focus(function(){

Please check snippet for more understanding.

$(document).ready(function(){
  $("button").click(function(){
    $("#newHTML").append('<input type = "text" placeholder = "some text .."/>');
  });
  $( document ).on( 'focus', 'input[type=text]', function() {
    $(this).addClass("focus");
  });
});
.focus
 {
   background-color: green;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<body>
  <div id = "newHTML"></div>
</body>
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
0

Yes you can. As long as you append html first then bind the event you want for it.

 $(document).ready(function(){
  $("button").click(function(){
//for safe calling lets add a class
    $("#newHTML").append('<input type = "text" placeholder = "some text .." class="inpt-class"/>');
  //after the input is add to the page add an event for it
  // either use or .on() or .focus()
  $("input.inpt-class").focus(function(){
    $(this).addClass("focus");
  });
  });
});
naviciroel
  • 422
  • 4
  • 19
0

If you use the appendTo method instead you can store your input-element in a variable and make changes to it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style = "txt/css"></style>
 <style>
 .focus
 {
   background-color: green;
 }
 </style>
 <script src = "alu_afric/Java/java.js"></script>
 <script>
$(document).ready(function(){
  $("button").click(function(){
    var input = $('<input type = "text" placeholder = "some text .."/>');
    input.appendTo("#newHTML");
    input.css('background', 'red');
  });
  $("input").focus(function(){
    $(this).addClass("focus");
  });
});
 </script>
 <button>Click</button>
<body>
<div id = "newHTML"></div>
</body>
knutesten
  • 594
  • 3
  • 16