Shiv Singh
Shiv Singh

Reputation: 7211

if statement issues with change

i am want to check dynamic value and variables that is Yes or No:

jQuery("select.super-attribute-select").change(function() {
  //console.log("New Product ID: " + this.value);
  var option_id11 = "Yes";
  var option_id12 = "No";
  var selectedvalue = this.value;

  //var optionvalue = "option_id"+selectedvalue;

  if ("option_id" + selectedvalue === "Yes") {
    console.log('hide');
  } else if ("option_id" + selectedvalue === "No") {
    console.log('show');
  } else {
    console.log('Nothing');
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="super_attribute[161]" data-selector="super_attribute[161]" data-validate="{required:true}" id="attribute161" class="super-attribute-select" aria-required="true">
  <option value="">Choose an Option...</option>
  <option value="11">REFURB</option>
  <option value="12">NEW</option>
</select>

but its always show Nothing in console. please help

Upvotes: 1

Views: 68

Answers (2)

Vishnu M
Vishnu M

Reputation: 1

jQuery("select.super-attribute-select").change(function() {
   var data = {
     option_id11:"Yes",
     option_id12:"No"
   }
   var selectedvalue = this.value;
   if (data["option_id"+selectedvalue] === "Yes") {
      console.log('hide');
   } else if (data["option_id"+selectedvalue] === "No") {
      console.log('show');
   } else {
      console.log('Nothing');
   }

});

Upvotes: 0

yadejo
yadejo

Reputation: 1968

You cannot call variables using strings representing the name of that variable. Try creating an object to specify the values instead:

jQuery("select.super-attribute-select").change(function() {
       //console.log("New Product ID: " + this.value);

        var options = {
          option_id11: "Yes",
          option_id12: "No"
        }

        var selectedvalue = this.value;

        var selectedOptionValue = options["option_id"+selectedvalue];

        if (selectedOptionValue === "Yes") {
            console.log('hide');
        } else if (selectedOptionValue === "No") {
            console.log('show');
        } else {
            console.log('Nothing');
        }

    });

Upvotes: 2

Related Questions