Using change() and contains() with an HTML <select> (jQuery)

I'm having some images change on the value change of a <select> dropdown. I've simplified the code here to get the general idea across. Here's what I've got (let me know if you have any questions; I know I haven't shown 'select_text' in here but I don't think it's entirely necessary and I'd have to unravel a bunch of code to simplify here):

var select_option_select = select_text.parent().find('select');

select_option_select.change(function(){
    var changed_value = select_text.parent().find('select option[value="' + $(this).val() + '"]').text();
});

//THIS IS WHERE THE IMAGE CHANGES
if(changed_value=="Standard Crossline Grips (free)"){
    $('#grip_image').attr('src','/v/vspfiles/images/grip_image.jpg');
}

I know this works but because of the way it's set up, the string of changed value has to be exact the same value as what I put in the IF statement. I've been trying to use 'contains' so it will give me more flexibility moving forward on the site. I know that I can't use 'contains' on a text() value so I re-wrote it like this (note that I get rid of the text() function):

var select_option_select = select_text.parent().find('select');

select_option_select.change(function(){
    var changed_value_2 = select_text.parent().find('select option[value="' + $(this).val() + '"]');
});

//THIS IS WHERE THE IMAGE CHANGES
if(changed_value_2.contains("Standard Crossline Grips (free)")){
    $('#grip_image').attr('src','/v/vspfiles/images/grip_image.jpg');
}

This gives me the error:

Uncaught TypeError: Object #<Object> has no method 'contains'

Which I guess means it's not recognizing any 'option' and changed_value_2 isn't actually returning anything?

I hope I've explained this well enough. Let me know if you have any questions. Thanks so much for your help.


This may be what you want:

if(changed_value.indexOf("Standard Crossline Grips") >= 0){
    $('#grip_image').attr('src','/v/vspfiles/images/grip_image.jpg');
}

or

if(changed_value.indexOf("(free)") >= 0){
    $('#grip_image').attr('src','/v/vspfiles/images/grip_image.jpg');
}

Source

链接地址: http://www.djcxy.com/p/74102.html

上一篇: 切换CSS背景颜色和图像

下一篇: 使用change()和contains()与HTML <select>(jQuery)