0

This is the code I am using in Wordpress latest version using jQuery 1.8.3

I want to limit the options to 3. Any ideas?

        <script type="text/javascript">
    jQuery(function($){
       $('ul.image_picker_selector li').click(function() {
        $(this).toggleClass('selected');

        if ($('.selected').length > 3) {
            $(this).toggleClass('selected');
            alert('You have already selected 3 items!' + ('\n') + 'You can undo a selection.');
        }
    });
    })
        </script>


    <ul class="thumbnails image_picker_selector">
<li class="selected">
<div class="thumbnail selected">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-1.jpg">
</div>
</li>
<li class=""><div class="thumbnail selected">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-2.jpg">
</div>
</li>
<li class="">
<div class="thumbnail">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-3.jpg">
</div>
</li>
<li class="">
<div class="thumbnail">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-4.jpg">
</div>
</li>
<li>
<div class="thumbnail">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-5.jpg">
</div>
</li>
<li>
<div class="thumbnail">
<img class="image_picker_image" src="http://www.style-card.co.uk/id/assets/img/signup/Q1-6.jpg">
</div>
</li>
</ul>

EDIT - This is the webpage that I am having problems with, if its any help. My knoweledge of jQuery is pretty poor unfortunately.

http://style-card.co.uk/id/register/

EDIT 2 - Have updated the code I am using.

Jeremy
  • 327
  • 1
  • 7
  • 17
  • Why add your own class to the options that are selected, when the `` tag has an attribute for this very feature? See my answer below for a much more streamlined approach... – Jason M. Batchelor May 21 '13 at 13:37
  • Thank you - Im not sure exactly what I am doing, but I will give it a go. Im wondering if the validation is not working because of a conflict with my image replacement plugin for the select options, – Jeremy May 21 '13 at 13:46
  • Urgh. Ok, it's because your select list is never touched by the user! – Jason M. Batchelor May 21 '13 at 13:51
  • Ok thanks, makes sense to me. Haha, now Ill have to figure out the way around it. – Jeremy May 21 '13 at 13:57
  • The /proper/ place for a fix would be in the image-picker plugin. I'm not sure you can override the plugin's behavior from outside the plugin itself. – Jason M. Batchelor May 21 '13 at 14:08
  • Ive updated the original question so that it includes the proper code. I am getting somewhere slowly as the validation sort of half works now. – Jeremy May 21 '13 at 14:13
  • Please see my updated answer, below. You're still trying to use .click() and that just isn't going to work out well. – Jason M. Batchelor May 21 '13 at 14:33

5 Answers5

1

There are a couple of issue with your code. First, see this question about how to limit the number of selections.

Second, you are attaching your event listener before the image-picker is available. Either move the script block below your select OR (and this is the best practice) wrap your statement in ready statement:

$(document).ready(function() {
    $('.image-picker').click(function() {
        ...
    });
});

The error messages you are seeing could be cause by a couple of things:

Are you sure jQuery has loaded when you are executing your script?

Are you using jQuery.noConflict?

Community
  • 1
  • 1
cfs
  • 10,610
  • 3
  • 30
  • 43
  • 1
    AFAIK, $('body').ready is not considered best practice anymore. `$(document).ready()` is better. `$(function() { // your on-DOM-ready code here })` seems to be the most common trend. Otherwise, however, you're right on which this analysis! – Jason M. Batchelor May 21 '13 at 13:29
  • @mori57 Thanks! Updated to document – cfs May 21 '13 at 13:36
  • I am using jQuery.noConflict, I assumed it was this that was causing the error message. – Jeremy May 21 '13 at 13:40
  • I have edited the question to include a link to the page, if that helps at all.? – Jeremy May 21 '13 at 13:42
  • @Jeremy Either replace `$` with `jQuery` or don't use `noConflict` and your errors should go away – cfs May 21 '13 at 13:43
  • Yes, I edited it to jQuery(function($){ but for some reason the validation still doesnt seem to trigger. – Jeremy May 21 '13 at 13:45
  • @Jeremy Use the question I linked to (http://stackoverflow.com/questions/4135210/html-multiselect-limit) to see how to properly do the validation – cfs May 21 '13 at 13:47
  • The problem is not reflected by the code he's posted. He's using a plugin that converts his select list into a bunch of images in a `
      ` ... he should be capturing the click events on those, /not/ on the select list!
      – Jason M. Batchelor May 21 '13 at 13:53
    • Yes, I have a feeling this is more what I need. http://jsfiddle.net/roXon/t7evz/2/ – Jeremy May 21 '13 at 14:01
    • 1
      Hmm... This is pretty different than the original question. I would suggest posting a new question if you're still having issues. – cfs May 21 '13 at 14:06
    1

    Ok. Click is now the event you /could/ use, but you still need to use .on(). The plugin you use makes changes to the DOM, and .click() is fragile... it does not work with dynamically added elements. Try something like this:

    jQuery(function($){
       $(document).on('click', 'ul.image_picker_selector li', function() {
        $(this).toggleClass('selected');
    
        if ($('.selected').length > 3) {
            $(this).toggleClass('selected');
            alert('You have already selected 3 items!' + ('\n') + 'You can undo a selection.');
        }
    });
    })
    

    The main problem here, however, is that it may not stop the selection. What you might want to try instead is looking for 'mousedown'. If you intercept mousedown, you can catch the selection before it's made, in theory, and cancel the selection if you're already at a count of three. In this case, you might want to do something like this:

    jQuery(function($){
       $(document).on('mousedown', 'ul.image_picker_selector li', function(evt) {
        evt.preventDefault();
        evt.stopPropagation();
    
        // get the number of items already selected:
        var ctSelected = $(this).siblings('.selected').length;
    
        if (ctSelected === 3) {
            alert('You have already selected 3 items!' + ('\n') + 'You can undo a selection.');
        } else {
            $(this).toggleClass('selected');
        }
    });
    })
    

    Unfortunately, I don't have time to jsFiddle this for an example, but hopefully this gives you an idea of an approach that might help you.

    [UPDATED] I had some free time today, and thought I'd twiddle around with the plugin code. See my jsFiddle example of how to use it: http://jsfiddle.net/mori57/L5EMy/ ... you can download the updated plugin from https://github.com/jbatchelor/image-picker

    Basically, add a data-limit to your select tag:

    <select class="image_picker" data-limit="3" ...etc>
    

    Then, in the code where you set up the image-picker, but before you instantiate the image-picker itself:

    var limitReached = function(){
        alert("Hit the limit! Please deselect an image if you want to choose another!");
    };
    
    $(".image_picker").imagepicker({
        limit_reached: limitReached
    });
    

    This means you should be able to get rid of all the other stuff (trying to capture and react to the mousedown event).

    Jason M. Batchelor
    • 2,951
    • 16
    • 25
    0

    would this work ?

    $('.image-picker').click(function() {
            if ($('.selected').length < 3) {
                $(this).toggleClass('selected');
            else
                alert('You have already selected 3 items!\nYou can undo a selection.');
            }
        });
    
    Laurent S.
    • 6,816
    • 2
    • 28
    • 40
    0

    If you're getting this error,

    Uncaught TypeError: Property '$' of object [object Object] is not a function  
    

    Than you must have a problem jQuery.js file. Check whether jQuery is loaded by typing jQuery or $ on console.

    $(function () {
        $('.image-picker option').click(function () {
            if ($(this).is(":selected")) {
                $(this).toggleClass('selected');
                if ($(this).siblings("option:selected").andSelf().length > 3) {
                    $(this).toggleClass('selected');
                    alert('You have already selected 3 items!' + ('\n') + 'You can undo a selection.');
                    $(this).removeAttr("selected");
                }
            }
        });
    });
    

    DEMO

    Okan Kocyigit
    • 13,203
    • 18
    • 70
    • 129
    • Yes I tried this and get no error when I use jQuery(function($){ instead of $(function () {, however the validation doesnt seem to operate properly. – Jeremy May 21 '13 at 13:43
    • Ok, I've updated it again. I forgot to undo last selection. Now It seems to be working. – Okan Kocyigit May 21 '13 at 14:03
    0

    Thanks to mori57 I've added this functionality to the newest version of the script

    https://github.com/rvera/image-picker/pull/6

    RVera
    • 216
    • 4
    • 3