Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-12-17
8
Medium Priority
?
995 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
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…

721 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