-2

I want to check if the selected contains "color-" or "image-" and show the appropriate .

http://codepen.io/anon/pen/jkxoE

megawac
  • 10,953
  • 5
  • 40
  • 61

3 Answers3

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:

Javascript StartsWith

Community
  • 1
  • 1
samvv
  • 1,934
  • 1
  • 18
  • 26
  • 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
    }

});

http://api.jquery.com/attribute-starts-with-selector/

megawac
  • 10,953
  • 5
  • 40
  • 61
Justin Lee
  • 909
  • 4
  • 9
  • 19