alioguzhan
alioguzhan

Reputation: 7917

jQuery select element "on change" doesn't work second time

I am not sure about what the bug is here. I am getting a JSON from server on each selection on select box. According to the JSON I am creating new form elements. On first selection, everything works fine, but second one doesn't trigger my event handler.

$('#planned_process').on('change', function(e){
  var $this = $(this);
  var parent = $(this).parents('.form-group').next();

  // if (e.added){
  $('.inserted-elm').remove();
  console.log('selected process :', $this.val());

  record = {
    ...,
    "tags":[
      "dummy-tag"
    ],
    "priority":1,
    "is_valid":true,
    "planned_start_time":"2014-01-01T21:01:00",
    "selected_recipies":[

    ],
    "planned_duration":"23",
    "created_date":"2014-08-19T06:45:15.669",
    "planned_input":[

    ],
    "last_editor":[
      "",
      ""
    ],
    "planned_output":[

    ],
    "created_by":[
      "",
      ""
    ],
    "planned_resources":[

    ]
  };
    _.each(record, function(val, key){
      var nameType = 'planned-process-disabled';
      var type = 'text';
      var elm = '<!-- start of element -->' +
          '<div class="form-group inserted-elm has-error"' +
          ' data-id="' + 'QQQ' + '">'+
          '<label for="process_' + key + '" class="col-sm-4 control-label">'+
          key + ' [' + nameType + '] '  + ' :</label>' +
          '<div class="col-sm-8">' +
          '<input name="parameter_values' + '" type="'+ type +'" id="' +
          key + '" ' + 'value="'+ val + '" ' +
          'class="form-control" disabled="disabled"/></div> </div>' +
          '<!-- end of element -->';
      parent.before(elm);
    });
});

Here is a jsbin example:

JSBIN

Upvotes: 3

Views: 1925

Answers (1)

tcooc
tcooc

Reputation: 21249

You have:

var parent = $(this).parents('.form-group').next();
//...
$('.inserted-elm').remove();

The $('.inserted-elm') also selects the element in parent, which means the code is appending to a removed element half the time. To fix it, swap the 2 statements:

$('.inserted-elm').remove();
//...
var parent = $(this).parents('.form-group').next();

Upvotes: 6

Related Questions