0

So i have a field ProvTrav that is originally an EditorBox in MVC , where i want to change to a select list when the field PaysTrav is equal to Canada.

This code worked to change the appearance of the editor box :

$("input[id$='ProvTrav']")
    .replaceWith('<select id="Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[0].IdentTravailleur.ProvTrav" name="Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[0].IdentTravailleur.ProvTrav" class="ProductDetailsQuantityTextBox">' +
        '<option value="NB">NB</option>' +
        '<option value="QC">QC</option>' +
        '<option value="AB">AB</option>' +
        '<option value="MB">MB</option>' +
        '<option value="PE">PE</option>' +
        '</select>');

But what if i want to use replaceWith ONLY if the PaysTrav field is equal to Canada in real time ?

What i tried without success (Note : this is in a $(document).ready(function () { :

$("input[id$='PaysTrav']").change(function () {
    var pays = $("input[id$='PaysTrav']")
    if (pays == "Canada" || pays == "canada" || pays == "CANADA") {
        $("input[id$='ProvTrav']")
            .replaceWith('<select id="Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[0].IdentTravailleur.ProvTrav" name="Formulaire.Detail.DetailCmp.ListeCmpt.ListeCmptETS[0].IdentTravailleur.ProvTrav" class="ProductDetailsQuantityTextBox">' +
                '<option value="NB">NB</option>' +
                '<option value="QC">QC</option>' +
                '<option value="AB">AB</option>' +
                '<option value="MB">MB</option>' +
                '<option value="PE">PE</option>' +
                '</select>');

    }

});
  • 1
    You would have to bind a keyup event to to paytrav and check if it's value is equal to canada, then run your code if it is (to get the value, you can use `.val()` - at the moment you are checking against a jquery object, not the value) – Pete Aug 27 '21 at 15:32
  • @Pete oof thanks this solved my problem haha thanks a lot.. –  Aug 27 '21 at 15:38
  • Use the `input` event, not the `change` event. Also, you should use `.on("input", function () { var pays = this.value; ... });`. While you can use `change` or `input`, it is less obvious that you use `off('input')` to remove event handlers in that case. See [Difference between “change” and “input” event for an `input` element](https://stackoverflow.com/q/17047497/215552) – Heretic Monkey Aug 27 '21 at 15:38

0 Answers0