0

I want to create a jquery plugin and use that for some HTML elements in my page. This is my HTML code :

<select class="test">
    <option>
        111
    </option>
    <option>
        222
    </option>
    <option>
        333
    </option>
</select>
<select class="test">
    <option>
        444
    </option>
    <option>
        555
    </option>
</select>

I want to use my plugin for select elements. This is my plugin sample :

(function ( $ ) {
        $.fn.testplug = function() {
            var res = "";
            this.children("option").each(function(){
                res+=$(this).text()+"#";
            });
            alert(res);
        };
    }( jQuery ));

And for using it :

$(".test").testplug();

Now i aspect to have two res values,one of them should be 111#222#333# and another should be 444#555#, but i have one result and it's 111#222#333#444#555#. What should i do for getting my desired result? Link to jsfiddle

2 Answers 2

1

You are selecting both so you must specify which one you want to use

$('.test:first').testplug() //111#222#333

and

$('.test:last').testplug() //444#555#

or

$('select').on('change',function(){
    $(this).testplug();
});

or you could loop through every .test like this

$('.test').each(function(){
$(this).testplug();
});

You can also rewrite the code like this, to loop through the lists then children and alert at the end of every list

 (function ( $ ) {
        $.fn.testplug = function() {
            this.each(function(){
                  var res = "";
                $(this).children('option').each(function(){
                          res+=$(this).text()+"#";
                });
                 alert(res);
            });
        };
    }( jQuery ));

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, it's working but i have more than 2 select elements,also i don't want to using 'change' event.
Check update @SamanGholami if you want to use your original code you can do this $('.test').each(function(){ $(this).testplug(); });
1

You mean 2 alert on one called plugin function ?

   $.fn.testplug = function() {
        $(this).each(function(){
           var res = "";
           $(this).children("option").each(function(){
              res+=$(this).text()+"#";
           });
           alert(res);
        });
    };

1 Comment

Thank you for your reply :) You should put res in loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.