4

I am using chosen prototype for select box. Now i want to fire onchange event on that select box. here is the link for chosen prototype

How to do this. please help me.

<script type="text/javascript" src="/js/Event.simulate.js"></script>
<script src="/js/prototype.js" type="text/javascript"></script>
<script src="/chosen/chosen.proto.js" type="text/javascript"></script>


<div class="side-by-side clearfix" style="margin-bottom:14px;">

        <select data-placeholder="Select Loacation"  class="chzn-select" tabindex="2" name="source">
          <option value="">Select Loacation</option>
          <option value="">option1</option>
          <option value="">option2</option>
        </select>
  </div>



Event.observe($(".chzn-select"),'change', function(){

//alert($(".chzn-select").chosen());

})
j0k
  • 22,600
  • 28
  • 79
  • 90
Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90

2 Answers2

12

In this line you have used $() with a class name, which it does not support.

Event.observe($(".chzn-select"),'change', function(){

A class name can be used multiple times so an array is returned from $$(), here is one way to work with arrays.

$$(".chzn-select").invoke('observe', 'change', function() {
    ...
});

I haven't used Chosen before; it's instructions say it needs to be setup so you might have to do this outside of the change event.

document.observe('dom:loaded', function() {
    $$(".chzn-select").each(function(select) {
        new Chosen(select);
    });
});
clockworkgeek
  • 37,650
  • 9
  • 89
  • 127
  • hi, its not working, can you give me an example with alert please, – Ramesh Kotha Dec 16 '11 at 19:41
  • Now that I've read a suitable [example](https://github.com/harvesthq/chosen/blob/master/example.proto.html) I see I was setting it up wrong. Here is [a minimal fiddle](http://jsfiddle.net/ZBKeW/) that works, to get it looking like the official one I had to link to [the same CSS](http://julesjanssen.github.com/chosen/css/chosen.css) but of course you can make your own. – clockworkgeek Dec 16 '11 at 20:43
  • hi everything is working fine, but i have two select boxes on the same page, so how to distinguish those? – Ramesh Kotha Dec 16 '11 at 21:35
  • Give them each an `id` attribute. – clockworkgeek Dec 16 '11 at 22:18
  • 1
    hi @clockworkgeek i want to update the second select box based on the first select box, can you give me small example please. – Ramesh Kotha Dec 17 '11 at 08:00
6

use the "addEventListener" method on the select box object.

EDIT - here's an example:

document.getElementById('selecboxid').addEventListener('change', SomeFunction(), false);
Krik
  • 445
  • 5
  • 15