简体   繁体   中英

input keyup jquery function does not work

I have a situation like the one below:

 var value = document.getElementById("value").value; if (value = 'a') { ('.setting').append('<input type="text" name="name" placeholder="carname">'); } elseif(value = 'b') { ('.setting').append('<input type="text" name="name" placeholder="fruitname">'); } $(document).ready(function() { $("input[name=name]").keyup(function() { alert("The text has been changed."); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="username" placeholder="your name"> <select id="value"></select> <div class="setting"></div> 

The problem I have is that when I change the input the alert does not trigger. Does anyone know were am I messing up?

You're trying to select an input whose name property is "name" , but the value you set in your HTML is name="username" .

$(document).ready(function(){
    $("input[name='username']").keyup(function(){
        alert("The text has been changed.");
    });
});

A better way yet is to give your input a unique id and select by that, so you don't have to use an attribute selector:

<input id="usernameInput" type="text" name="username" placeholder="your name">
$("#usernameInput").keyup(function(){ ... });

The $ is missing from ('.setting') , you should use .on to catch events of dynamically created elements and it's better to use it with classes, also use == or more likely === for conditions.

Live example

Your code modified:

<input type="text" name="name" class="example" placeholder="your name">
<select id="value"></select>
<div class="setting"></div>

<script>
  var value = document.getElementById("value").value;
  if(value==='a'){
    $('.setting').append('<input type="text" name="name" class="example" placeholder="carname">');
  }

  else if(value==='b'){
    $('.setting').append('<input type="text" name="name" class="example" placeholder="fruitname">');
  }
</script>

<script>
 $(document).ready(function(){
   $('body').on('keyup', '.example', function() {
     alert("The text has been changed.");
   });
 });
</script>

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