Using the Select 2 plugin - How to disable select click

Asked

Viewed 539 times

1

My page:

<!DOCTYPE html>
<html>
<head>
    <title></title>

<!-- 3 coisas para o plugin funcionar  -->


<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="dist/css/select2.css">
<link rel="stylesheet" type="text/css" href="dist/css/select2.min.css">

<script type="text/javascript" src="vendor/jquery-2.1.0.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.js"></script>
<script type="text/javascript" src="dist/js/popper.min.js"></script>
<script type="text/javascript" src="dist/js/select2.full.js"></script>
<script type="text/javascript" src="dist/js/select2.full.min.js"></script>


</head>


<body>

    <div class="col-md-8 col-md-offset-2">
    <br>
        <select class="js-example-data-ajax form-control">
        </select>

    </div>

<script type="text/javascript">

      $(".js-example-data-ajax").select2({

          ajax: {
            url: "https://api.github.com/search/repositories",
            dataType: 'json',
            delay: 250,
            data: function (params) {
              return {
                q: params.term, // search term
                page: params.page
              };
            },
            processResults: function (data, params) {
              // parse the results into the format expected by Select2
              // since we are using custom formatting functions we do not need to
              // alter the remote JSON data, except to indicate that infinite
              // scrolling can be used
              params.page = params.page || 1;

              return {
                results: data.items,
                pagination: {
                  more: (params.page * 30) < data.total_count
                }
              };
            },
            cache: true
          },

          placeholder: 'Search for a repository',
          escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
          minimumInputLength: 1,
          templateResult: formatRepo,
          templateSelection: formatRepoSelection

        });

        function formatRepo (repo) {

          if (repo.loading) {
            return repo.text;
          }

          var markup = "<div class='select2-result-repository clearfix'>" +
            "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' width='100' height='50' /></div>" +
            "<div class='select2-result-repository__meta'>" +
              "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

          if (repo.description) {
            markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
          }

          markup += "<div class='select2-result-repository__statistics'>" +
            "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks<button class='btn btn-success' onclick='alert(1)'>Teste</button></div>" +
            "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
            "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
          "</div>" +
          "</div></div>";

          return markup;
        }

        function formatRepoSelection (repo) {
          return repo.full_name || repo.text;
          alert(repo.full_name || repo.text);
        }


</script>

</body>




</html>

You know, what happens. When I look for a text it comes back to me based on the html I built, however I need to put buttons in these "returns" as in the image

button-less:

inserir a descrição da imagem aqui

buttoned up:

inserir a descrição da imagem aqui

put an Alert at the click of this button, but I can’t click because I don’t know "How to disable select click".

1 answer

1


Select2 uses jQuery, so you can use the delegation to control and apply the preventDefault, being like this:

$(document).on("click", ".select2-result-repository button", function (e) {
     e.preventDefault();

     alert(1);
});

And remove onclick from button, use only in event:

"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks<button class='btn btn-success'>Teste</button></div>" +

However if each button needs to pass a value or pick from within the element .select2-result-repository__statistics (assuming there is more than one element with this class), you can do so:

$(document).on("click", ".select2-result-repository button", function (e) {
     var statistics = $(this).parents(".select2-result-repository__statistics");

     if (statistics.length) {
         e.preventDefault();

         //Pegando os elementos desejados
         console.log($(".select2-result-repository__forks"));
         console.log($(".select2-result-repository__stargazers"));
         console.log($(".select2-result-repository__watchers"));
     }
});

Note that if e.preventDefault(); not working will have to use stopPropagation that will stop the propagation of events, should stay like this:

$(document).on("click", ".select2-result-repository button", function (e) {
     e.preventDefault();
     e.stopPropagation();

     alert(1);
});

Or (depending on how you use it):

 if (statistics.length) {
     e.preventDefault();
     e.stopPropagation();

     //Pegando os elementos desejados
     console.log($(".select2-result-repository__forks"));
     console.log($(".select2-result-repository__stargazers"));
     console.log($(".select2-result-repository__watchers"));
 }
  • I tried to put here, but did not cancel

  • @Juliohenrique97 nor the stopPropagation? Strange, I’ll run some tests and let you know.

  • unfortunately no, is it because of the plugin Select2 ? @Gui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.