I want to check if the selected contains "color-" or "image-" and show the appropriate .
Asked
Active
Viewed 160 times
-2
-
Please post relevant code samples. What do you mean by `selected contains` ? – Rajaprabhu Aravindasamy Nov 23 '13 at 21:39
3 Answers
1
I think what you ment was really to check if some string contains given substring. You can do the following:
childValue.indexOf('color-');
If the substring is present it will return the index where this substring appeared, if not it will return -1.

kaapa
- 507
- 4
- 12
1
This issue has not really anything to do with jQuery but rather with JavaScript itself. The "most clean" way would be to extend the String prototype in JavaScript with a startsWith-procedure:
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
Next you can use the new procedure with any string you want:
if(childValue.startsWith ("color-")){
//show pickColor div
}
Should you discover a better method to compare the beginning of a string you can simply change the prototype declaration once. That's far easier than changing every occurence of whatever you choose to use in the rest of your code.
Sources:
-
But! Now I'm confused, `str.indexOf('color-') === 0` does exactly the same thing ? – adeneo Nov 23 '13 at 21:56
-
Hey adeneo, yes but apparently this.slice(0, str.length) == str; is a lot faster then str.indexOf('color-') === 0 http://stackoverflow.com/a/646643/1173521 – samvv Nov 23 '13 at 22:53
0
Maybe use something like this?
$(selectChild).on('change',function(){
var childOption = $("option:selected", this);
if (childOption.is('[value^=color]')) {
//show pickColor div
} else if (childOption.is('[value^=image]')) {
//show Upload div
}
});

megawac
- 10,953
- 5
- 40
- 61

Justin Lee
- 909
- 4
- 9
- 19