0

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?

3
  • $("input[name=name]") should be $("input[name=username]"). Typo. Commented Jun 20, 2018 at 14:45
  • 1
    You also have if (value = 'a') instead of if (value == 'a') and elseif instead of else if. And missing $s $('.setting') Commented Jun 20, 2018 at 14:46
  • 1
    well you've a lot of typos, fix it and try. Commented Jun 20, 2018 at 14:50

2 Answers 2

1

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(){ ... });
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.