Solved

2 select 2 boxes on same page - 2nd one not work

Posted on 2014-12-17
8
914 Views
Last Modified: 2014-12-23
hi

i have 2 select2 boxes on the same page. I want an alert saying 'no matches found' and it works perfect. The identical code on the second select does not work. I have no idea why

Here is the code

Any help is much appreciated. (ive removed what i beieve to be irrelevant code)

DOCTYPE html>
....
        <link href="bootstrap/css/select2.css" rel="stylesheet"/>
    </head>

    <body>
        <?php
        include 'dbconnect.php';
        ?>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script src="js/select2.min.js"></script>

        <select id="tags">
            <?php
            foreach ($conn->bloodgroup() as $row) {
                echo "<option value='" . $row["id"] . "'>" . $row["bloodtype"] . "</option>";
            }
            ?>
            }
            </br>
            </br>
        </select>

        <input type="hidden" id="bgselect" value="" style="width: 200px;">

     
   <script>
            $(document).ready(function () {
            
        $("#tags").select2({
                    width: '240px',
                    allowClear: true,
                    formatNoMatches: function (term) {
                        alert("no matches tags box");
                        return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
                    /* add the new term */
                    var newTerm = $('#newTerm').val();
                    //              alert (newTerm);

                    $('<option>' + newTerm + '</option>').appendTo('#tags');
                    $('#tags').select2('val', newTerm); // select the new term
                    $("#tags").select2('close'); // close the dropdown

                    $.ajax({
                        type: "POST",
                        url: "addblood.php",
                        data: {
                            bloodtype: newTerm
                        },
                        cache: false,
                        success: function (result) {
                            alert(result);
                        }
                    })
                });
                
                $("#bgselect").select2({
                  
                    ajax: {
                        url: 'fillblood.php',
                        dataType: 'json',
                        type: "GET",
                        quietMillis: 50,
                        data: function (term) {
                            return {
                                term: term
                            };
                        },
                        results: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.text,
                                        id: item.id
                                    }
                                })
                            };
                        }
                    },
                    formatNoMatches: function (term) {
                        alert("No Matches bgselect box");
                        return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn btn-default'>Create</a>";
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
                    var newTerm = $('#newTerm').val();
                    $('<option>' + newTerm + '</option>').appendTo('#bgselect');
                    $('#bgselect').select2('val', newTerm); // select the new term
                    $("#bgselect").select2('close'); // close the dropdown
                });
                      
});
        </script>

Open in new window


The second select2 does not work here

 formatNoMatches: function (term) {
                        alert("No Matches bgselect box");
                        return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn btn-default'>Create</a>";
                    }
Any help much appreciated. Happy Christmas (or just Happy Spiritual Day)


EDIT (FROM DOCS)
==========
https://ivaynberg.github.io/select2/#documentation

a few references to the needed use of a hidden input

n order to take advantage of custom data loading Select2 should be attached to an input type='hidden' tag, otherwise data is parsed from select's option tags.

The sorting is only available when Select2 is attached to a hidden input field.

When used in combination with input[type=hidden] tag care must be taken to sanitize the id attribute of the choice object, especially stripping , as it is used as a value separator.

and this is referenced when needing to populate using ajax
In order for this function to work Select2 should be attached to a input type='hidden' tag instead of a select.
0
Comment
Question by:andieje
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
8 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40505183
check the console to see the error, provide a link to see your page
be sure to validate your page with this tools : http://validator.w3.org/
0
 

Author Comment

by:andieje
ID: 40505737
there no error otherwswe i would felt it germane to post this crucial tidbit of information. No error in ie chrome or firefox

Code was ran thgough a validator before posting. To not do that would be lazy
0
 

Author Comment

by:andieje
ID: 40505816
whole page if it helps

<!DOCTYPE html>
<html>
    <head>
        <link href="bootstrap/css/select2.css" rel="stylesheet"/>
        <title>example</title>
    </head>

    <body>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script src="js/select2.min.js"></script>

 
        <input type="hidden" id="bgselect" value="" style="width: 200px;">

        <script>
            $(document).ready(function () {
                $("#bgselect").select2({
                    ajax: {
                        url: 'fillblood.php',
                        dataType: 'json',
                        type: "GET",
                        quietMillis: 50,
                        data: function (term) {
                            return {
                                term: term
                            };
                        },
                        results: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.text,
                                        id: item.id
                                    }
                                })
                            };
                        }
                    },
                    formatNoMatches: function (term) {
                        alert("No Matches bgselect box");
                        return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn btn-default'>Create</a>";
                    }
                }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
                    var newTerm = $('#newTerm').val();
                    $('<option>' + newTerm + '</option>').appendTo('#bgselect');
                    $('#bgselect').select2('val', newTerm); // select the new term
                    $("#bgselect").select2('close'); // close the dropdown
                });
                     
});
        </script>


    </body>

</html>

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:andieje
ID: 40505836
There is  a missing semi colon on lin33
0
 
LVL 43

Expert Comment

by:Rob
ID: 40506605
There isn't anything wrong with your code, see here for a working example: http://jsbin.com/hoduge/2/edit?js,output that uses output from this: http://jsbin.com/bosora/1.js

So it could be a conflict with your #tabs Select2
0
 

Accepted Solution

by:
andieje earned 0 total points
ID: 40508133
It was because the ajax query was never reducing the results so it never got to No Results section. I didnt realise the select2 always bought back all results with ajax. It appears i have to do as this page shows

https://github.com/ivaynberg/select2/wiki/PHP-Example
0
 

Author Comment

by:andieje
ID: 40513823
sorry this isnt solved

takng this code from comment ID: 40506605

if you type i an item that isnt in the list this code isnt triggered

 formatNoMatches: function (term) {
      alert("No Matches bgselect box");
      return "<input class='form-control' id='newTerm' value='" + term + "'><a href='#' id='addNew' class='btn btn-default'>Create</a>";
    }
  }).parent().find('.select2-with-searchbox').on('click', '#addNew', function () {
    var newTerm = $('#newTerm').val();
    $('<option>' + newTerm + '</option>').appendTo('#bgselect');
    $('#bgselect').select2('val', newTerm); // select the new term
    $("#bgselect").select2('close'); // close the dropdown
  });

});
0
 

Author Closing Comment

by:andieje
ID: 40514588
I solved the issue.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question