Mohamed Nefzi
Mohamed Nefzi

Reputation: 11

How to trigger the change event on the input when I choose the option from select using jQuery?

I use jQuery to trigger an event in my project. I want to trigger an input event change when I choose an option from the select and when I choose an option the input value will be changed with the option value and show the length of the new value.

Also, I want to trigger an event change in the input but it does not work for me, I try many times but does not work :

$(document).ready(function() {
  var oldVal;
  var checkLength = function(val) {
    $('label').html(val.length);
  }

  $('input').bind('change textInput input', function() {
    var val = this.value;
    if (val !== oldVal) {
      oldVal = val;
      checkLength(val);
    }
  });

  $("select").change(function() {
    var str = "";
    $("select option:selected").each(function() {
      str += $(this).text() + " ";
    });
    $("input").val(str);
  })
}); 

Upvotes: 1

Views: 1889

Answers (2)

Muhammad Usman
Muhammad Usman

Reputation: 10148

This is how I would have done that.

  1. Add change event listeners on both.
  2. Update input with the value selected in select tag
  3. Trigger change event from there

$("#s").change(function(){
   console.log("Option selected");
   $("#d").val($(this).val());
   $("#d").trigger("change");
});

$("#d").change(function(){
  console.log("input modified")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="d" />

<select id="s">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

Upvotes: 2

patilprashant6792
patilprashant6792

Reputation: 353

Try manually triggering the change event of input like this

*$( "input" ).trigger("change");*

Upvotes: 1

Related Questions