Annie Lagang
Annie Lagang

Reputation: 3235

How to split the selected value from dropdownlist and use it as a selector in jquery

If my title seems stupid, forgive me. I'm a newbie in jQuery and I don't know to explain my problem using the correct jQuery terms.

So I asked this question a while ago and got the perfect answer. My problem now is that the value in my dropdownlist is not that simple and the solution given to me fails because of that.

The code given to me was $("select[id*='ComboBox'][value!=0]").length + offset;. In my sample code that's fine because the values are 0, 1, 2, 3. But in reality the values are like default_price1, code1_price2, code2_price3... So basically the values are concatenated strings. I know how to split strings but my problem now is how do I integrate that with my previous code?

$("select[id*='ComboBox'][value.split('_')[0]!==default]").length + offset; doesn't seem to work.

Is that even possible? Thanks again.

Here's the jsfiddle as requested: http://jsfiddle.net/annelagang/scxNp/20/

Upvotes: 0

Views: 2231

Answers (3)

Umesh Patil
Umesh Patil

Reputation: 10695

$(function() {
    $("select[id*='ComboBox']").change(function() {
        var sum=0;
        $(this).find("option").each(function(){
          sum+=parseInt($(this).val().split("price")[1]);        
        });     
        $("#total").text(sum);
    });
});

If user selects any value from dropdown. Sum is dispalyed (1+2+3+4)=10

You can use string spliting logic in your way. but , Is it what you wanted ?

Upvotes: 0

Ivan Castellanos
Ivan Castellanos

Reputation: 8251

Don't abuse jQuery selectors, better use the filter method.

$("select[id*='ComboBox']")
   .filter(function(){return this.value.replace(/_.*/,"") !== "default"}).length
   + offset;

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150080

If the following works for value of "0":

$("select[id*='ComboBox'][value!=0]").length + offset

Then for values beginning with "default" you should be able to do something like this:

$("select[id*='ComboBox']").not("[value^='default']").length + offset

Where ^= is "starts with".

But you could use the .filter() method, which would allow you to do whatever kind of string manipulation you like to test whether each item should be included:

$("select[id*='ComboBox']").filter(function() {
   return /^default/.test($(this).val());
}).length + offset

/^default/ is a regex that looks for "default" at the beginning of the string.

Upvotes: 1

Related Questions