Solved

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

Posted on 2014-12-17
8
660 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
  • 6
8 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:andieje
Comment Utility
There is  a missing semi colon on lin33
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I solved the issue.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to dynamically set the form action using jQuery.
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)

728 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now