samedi 25 novembre 2017

jquery javascript variable of the if-statement is not seen in else-Statement

A small form should be used to make sure that selecting a specific element influences the selection of additional form fields. To solve the problem I used the jQuery Change function. With an If-Else Statement the desired results are delivered. However, the change function does not return the desired result if the special variable 'shippingLocalPickup' is only declared within the IF statement. (JS-FIDDLE)

<INPUT type="checkbox" id="checkboxNationalShippingService" name="checkboxNationalShippingService" value="yes" checked="checked" />
<select id="shippingServiceSel" name="shippingService">
  <option selected value='DE_Pickup'>Ware muss abgeholt werden</option>
  <option selected value='DHL_Paket'>Paket</option>
</select>
<div id="shippingLocalPickup" class="selElement" title="Diese Option sollte bei ja belassen werden">
  <p>Artikel kann abgeholt werden?
    <select name="shippingLocalPickup">
      <option selected value="DE_Pickup">ja</option>
      <option value="false">nein</option>
    </select>
  </p>

the query script:

  $(document).ready(function() {
    $("#shippingServiceSel")
      .change(function() {
        var shippingService = $("#shippingServiceSel").val();
        if (shippingService == "DE_Pickup") {
          var shippingLocalPickup = $("#shippingLocalPickup");
          shippingLocalPickup.empty().append('<p>Artikel kann abgeholt werden? <select name="shippingLocalPickup"><option value="false">nein</option><option value="true">ja</option></select></p>');
        } else {
          shippingLocalPickup.empty().append('<p>Artikel kann abgeholt werden? <select name="shippingLocalPickup"><option value="true">ja</option><option value="false">nein</option></select></p>');
        }
      })
  });

If it is declared at the beginning of the function, everything works fine. (JS-FIDDLE)

  $(document).ready(function() {
    $("#shippingServiceSel")
      .change(function() {
        var shippingLocalPickup = $("#shippingLocalPickup");
        var shippingService = $("#shippingServiceSel").val();
        if (shippingService == "DE_Pickup") {

          shippingLocalPickup.empty().append('<p>Artikel kann abgeholt werden? <select name="shippingLocalPickup"><option value="false">nein</option><option value="true">ja</option></select></p>');

        } else {
          shippingLocalPickup.empty().append('<p>Artikel kann abgeholt werden? <select name="shippingLocalPickup"><option value="true">ja</option><option value="false">nein</option></select></p>');
        }
      })
  });

In my opinion, variables should be visible everywhere within a function. As described here: (stackoverflow article)

Why is visibility still restricted in the if statement? Where is my mistake? Thanks in advance...


Aucun commentaire:

Enregistrer un commentaire