Justine M
Justine M

Reputation: 139

Adding another option when the select dropdown is clicked?

I need to add a new select option in my HTML when they click it

<select class="statusButtonChange statusButton " data-value="49506">
    <option value="0" selected=""></option>
    <option value="1">Close</option>
    <option value="2" disabled="" style="color:grey;">Taken</option>
</select>

This new option is dynamic and will be coming from an API response... I'm parsing the var value from the API response but for now, I made it static just to test.

Right now, I have this:

$(document).ready(function () {
    var k = 1
    $(".statusButton").on('focus', function () {
        var value = "Disable";
        var new_v = "";
        var html = $(".statusButton").html();

        if (k == 1) {
            if (value == "Disable") {
                new_v = "<option value='Disable' >Disable</option>";
            }
            else if (value == "Enable") {
                new_v = "<option value='Enable' >Enable</option>"
            }
            var full = html + "" + new_v;
            $(".statusButton").html(full);
            k = 2;
        }
    });
});

It is working on JSFiddle but when I try to integrate it on my website, it's not reading it, even just the console log. WHat am I doing wrong?

Upvotes: 1

Views: 913

Answers (2)

Aishwarya
Aishwarya

Reputation: 645

This is short answer without creating too many variable.

$(document).ready(function() {
  var k = 1
  $(".statusButton").on('focus', function() {
    var value = "Disable";
    if (k == 1) {
      if (value == "Disable") {
        $(".statusButton").append("<option value='Disable' >Disable</option>");
      } else if (value == "Enable") {
        $(".statusButton").append("<option value='Enable' >Enable</option>")
      }
      k = 2;
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="statusButtonChange statusButton " data-value="49506">
  <option value="0" selected=""></option>
  <option value="1">Close</option>
  <option value="2" disabled="" style="color:grey;">Taken</option>
</select>

Upvotes: 0

machineghost
machineghost

Reputation: 35807

I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).

Consider:

...
$(".statusButton").on('focus', function () {
    var value = "Disable";
    var new_v = "";
    var $statusButton = $(".statusButton");
    if(k == 1){
        if(value == "Disable")
        {
            $statusButton.append("<option value='Disable' >Disable</option>");
        }
        else if(value == "Enable")
       {
           $statusButton.append("<option value='Enable' >Enable</option>")
       }
...

If you do things that way, you don't have to mess around with any extra .html calls.

Upvotes: 2

Related Questions