alba hoo
alba hoo

Reputation: 164

how to chain jQuery onchange event like?

input#one
input#two
input#three

$('#one').change(function() {
  $('#two').val('change_by_one');
});

$('#two').change(function() {
  $('#three').val('changed');
});

I want to chain the change event, so when I change #one, it will change #two then #three ... I tried

$('#one').change(function() {
  $('#two').val('change_by_one');
  // at this point, the changed value of `#two` is not rendered yet, resulting some invalid state.
  $('#two').trigger('change'); 
});

Any idea how to achieve that? Chain events

==============update=============== a better example to my issue is:

<select id="organisation">
    <option value="org1">org1</option>
    <option value="org2">org2</option>
</select>

<select id='media'>
</select>

<input placeholder="get the selected media"/>

var $media = $('#media');
$('#organisation').change(function() {
  var options = [];
  setTimeout(function() {
    $media.append('<option value="image" data-type="image">image</option>');
    $media.append('<option value="first" data-type="video">video</option>');
  }, 1000);
    $media.change();
});

$('#media').change(function() {
  $('input').val($('#media').val());
});

Select organisation do ajax call to get it's media files, and render the options in the media select, I just want some onchange event for media field triggered when organisation is changed.

I have make an example. https://jsfiddle.net/rht3Lxav/

============= solution ==========

var $media = $('#media');

$('#organisation').change(function() {
  var options = [];
    AddOptions().then(function() {
        $media.change();
    });
});

$('#media').change(function() {
  $('input').val($('#media').val());
});

function AddOptions() {
    return new Promise(function(resolve, reject) {
    setTimeout(function() {
    $media.find('option').remove().end();
        $media.append('<option value="image" data-type="image">image</option>');
        $media.append('<option value="first" data-type="video">video</option>');
      resolve();
    }, 1000);
  });
};

Thanks!

Upvotes: 1

Views: 1266

Answers (1)

Pierre-Adrien Maison
Pierre-Adrien Maison

Reputation: 610

You can do like that :

$('#one').change(function() {
  $('#two').val('change_by_one').change();
});

$('#two').change(function() {
  $('#three').val('change_by_two').change();
});

$('#three').change(function() {
  $('#four').val('change_by_three');
});

You can test it here : https://jsfiddle.net/m2gb3yj1/9/

Upvotes: 2

Related Questions