Scott P
Scott P

Reputation: 31

jQuery replacewith varibles not getting replaced on change

On dropdown change the variable val is not getting changed in the replacewith. It is still set to the initial value but not getting updated.

alert(val) does give the correct value. delete val does not help either.

$(document).ready(function() {
  $("#answerDropdown").change(function() {
      var val = $(this).val();
      if (val != '') {
        $("#filler").replaceWith('<div id="replaced"> ' + val +  '</div>');
        alert(val);
        delete val;
      }
  });
});

Fiddle

Upvotes: 0

Views: 38

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

The problem is after the first change you are REPLACING div with id='filler'

Therefore 2nd and subsequent onchange there will not be an element with id='filler' - so that code just doesn't run

you can do this instead

$("#filler").html('<div id="replaced"> ' + val +  '</div>');

This will result in the filler div having an inner div

or

$("#filler").replaceWith('<div id="filler"> ' + val +  '</div>');

which is identical to

$("#filler").text(val);

Upvotes: 3

Related Questions