1

I'm trying to add and remove a div depending on the value of a select menu. This code works well a first: when the value of the select is 2 div appears. When I return to the first value (1), the div disappears. However if I select the value 2 again, the div is not add again. Any idea ?

 <select id="interv_base_youorthird" name="interv_base[youorthird]" class="form-control">
      <option value="1">Pour moi</option>
      <option value="2">Pour un tiers</option>
</select>
<input type="hidden" id="extra-counter" value="0">
$("#interv_base_youorthird").change(function(){
    if( $(this).val() == "2" ){
        const index = +$('#extra-counter').val();

        const tmpl = 'hello world';
        //Add sub form
        $('#interv_base_intervExtras').append(tmpl);

        $('#extra-counter').val(index + 1);
    }
    else{
        $('#interv_base_intervExtras').remove();
    }
});
1
  • Can you please add full code which you tried. some of your variables/elements are undesigned. Commented Dec 2, 2019 at 10:02

1 Answer 1

4

The problem is because you remove() the #interv_base_intervExtras element when you select the first option again. When you move back to the second option #interv_base_intervExtras no longer exists in order to read the data-prototype attribute from it.

To fix this use empty(), instead of remove(), to clear the content of the element instead of removing the entire element:

var $interv = $('#interv_base_intervExtras');

$("#interv_base_youorthird").change(function(){
  if ($(this).val() === "2") {
    const index = parseInt($('#extra-counter').val(), 10);
    const tmpl = $interv.data('prototype').replace(/__name__/g, index);
    $('#interv_base_intervExtras').append(tmpl);
    $('#extra-counter').val(index + 1);
  } else {
    $('#interv_base_intervExtras').empty(); // <-- amend this
  }
});

Note that I amended the logic slightly in the above example to cache the #interv_base_intervExtras element and to explicitly use parseInt() instead of coercing the string to an int using the + operator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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