0

I need to change the ID of an input text to use two functions of keyup with Jquery, for example I select the option number 1 and on my script I write a function keyup for id 1and other for the number 2, to know if it works I use alert, but always work the id put by default.

$('#selector').change(function() {
  $('#1,#2').attr('id', $(this).val());
});
$(document).ready(function() {
  $('#1').keyup(function() {
    alert("OPTION 1 SELECTED");
  });
  $('#2').keyup(function() {
    alert("OPTION 2 SELECTED");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="selector">
  <option>1</option>
  <option>2</option>
</select>
<input id="1" type="text">

What wrong?

0

2 Answers 2

0

You're binding to the elements based on their original IDs. If you want the bindings to follow changing IDs you have to use event delegation.

$('#selector').change(function() {
  $('#1,#2').attr('id', $(this).val());
});
$(document).ready(function() {
  $(document).on("keyup", '#1', function() {
    alert("OPTION 1 SELECTED");
  });
  $(document).on("keyup", '#2', function() {
    alert("OPTION 2 SELECTED");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="selector">
  <option>1</option>
  <option>2</option>
</select>
<input id="1" type="text">

But this seems like a strange way to do this. Why not just use a single handler that does

alert("Option " + $("#selector").val() + " selected");
3
  • great it work perfectly!! Have a great day, you helped me!! ^ ^ Apr 26, 2020 at 14:54
  • @user13411530 do not use thanks, it worked etc. just mark the answer as answered or upvote the answer, or both Apr 26, 2020 at 14:59
  • @BryanDellinger and you add a comment when neccessary, this web allow vote after x minutes of answered ; ) Apr 26, 2020 at 15:04
0

Hope this will help

$(document).ready(function() {
  $('#selector').change(function() {

    $('#1,#2').attr('id', this.value);
  });

  $('input[type="text"]').keyup(function() {
    alert("OPTION "+$(this).attr('id')+" SELECTED");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="selector">
  <option value="1">1</option>
  <option value="2">2</option>
</select>
<input id="1" type="text">

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.