rabid_zombie
rabid_zombie

Reputation: 992

Changing value of custom select option - Javascript

I need assistance changing the value of a custom-select box. I cannot use JQuery because I already have a change() function hooked up to it.

How can I change the value of the select box in Javascript?

This is my custom select function:

$.fn.customSelect = function() {
if ( $(this).length ) {
    $(this).find('select').attr('selectedIndex',-1).change(function() {
        var optionText = $(this).find('option:selected').text();
        $(this).siblings('label').text(optionText)
    });
}

};

I have tried:

var field = document.getElementById('test5');
field.value = '2';
field.focus();

This will select the option, but it will not show up as the default option (hopefully you guys can understand this haha).

Any possible solutions?

Upvotes: 1

Views: 4236

Answers (1)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

I made a fiddle example of what trying to do here

You need to invoke the change event to run the plugin code, also name the change event:

$.fn.customSelect = function() {
    if ( $(this).length ) {
        $(this).find('select').attr('selectedIndex',-1).bind('change.customSelect', function() {
            var optionText = $(this).find('option:selected').text();
            $(this).siblings('label').text(optionText)
        });
    }
};

Trigger like this:

$('#select1').val('1').trigger('change.customSelect');

Upvotes: 2

Related Questions