0

I got a problem. I've tried to do a selectbox using boostrap form helpers.(http://js.nicdn.de/bootstrap/formhelpers/docs/state.html)

So I got a selectbox for "country" and an other for "state"

<select id="countries" class="form-control bfh-countries"></select>
<select id="states" class="form-control bfh-states" data-country="countries"></select>

If I choose a value form the country box the states appears in the states box, so everything ok.

But if I use a script

<button onclick="test()" class="btn">Load Country</button>

function test(){
            document.getElementById('countries').value = "AU";
        }

Nothing appends on the "states" selectbox, I should get the states of the country selected by the function test() right ?

What can I do to fix this ?

http://jsfiddle.net/xf8ech7k/1/

Thanks in advance

Pierre
  • 675
  • 1
  • 8
  • 18

1 Answers1

0

The problem there is that you aren't triggerent the "change" event.

Take a look at you modified code

function test(){
    var select = document.getElementById('countries')
    , event = document.createEvent("UIEvents");
    select.value = "AU";
    event.initUIEvent("change", true, true);
    select.dispatchEvent(event);
}

Then, take a look at this post

As @CBroe says, you can do it in a simpler way by doing:

$("select").val("AU").trigger("change");
Community
  • 1
  • 1
Mindastic
  • 4,023
  • 3
  • 19
  • 20
  • 1
    Since bootstrap uses jQuery already, that could be done much simpler, `$('#countries').val('AU').trigger('change');` – CBroe Jul 11 '15 at 02:57
  • Thanks a lot, been 2 days I was searching :( and thanks for the link !! Cheers – Pierre Jul 11 '15 at 03:05
  • @Mindastic I've tried to modify my form with a flag in the selectbox, but when I trigged the value the flag don't appears, I just got the value. Is there something to add in this case ? http://jsfiddle.net/xf8ech7k/2/ – Pierre Jul 11 '15 at 03:56
  • Given the fact that it is a custom plugin, you could do something like this: $('#countries').find('[data-option=AU]').trigger('click'); – Mindastic Jul 11 '15 at 04:09
  • Works Perfect :) so trigger() can have different parameters, can we add like focus, blur ... is there any restrictions ? I'm going to play with trigger() – Pierre Jul 11 '15 at 04:18
  • Yup, you can also trigger custom events. Check ".trigger()" doc for more information: http://api.jquery.com/trigger/ – Mindastic Jul 11 '15 at 04:19
  • Thank you so much, it's pretty powerful ^^ Cheers – Pierre Jul 11 '15 at 04:33