3
var id    = $('.getval_'+product_id+''+index+'').attr("id");
var value = "";

console.log(id);
//data that return by id
6059
s2id_6061
6122
s2id_8410

if (id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{      
    value = $('.getval_'+product_id+''+index+'').val();
}

Question: The code above is show that when the ID return by jquery, then it will show a list of data, so what I want is when the ID return, if the in front of ID don't have s2id_ it will go else statement. But the code return an error which is (Uncaught TypeError: Cannot read property 'indexOf' of undefined)

1
  • 1
    +''? This is not needed at any point in your code. Commented Jun 9, 2017 at 3:04

1 Answer 1

4

You need to check whether id itself is set, and there are two ways of going about this.

Either chain the if (id.indexOf('s2id_') > 0) condition inside an outer if condition that checks for id:

if (id) {
    if (id.indexOf('s2id_') > 0) {
        value = $('.getval_'+product_id+''+index+'').select2('val');
    }else{      
        value = $('.getval_'+product_id+''+index+'').val();
    }
}

Or check for both conditions with an and statement:

if (id && id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{      
    value = $('.getval_'+product_id+''+index+'').val();
}

Hope this helps! :)

Sign up to request clarification or add additional context in comments.

5 Comments

if (&& id.indexOf('s2id_') > 0) this should be if (id.indexOf('s2id_') > 0)
It's important to check id as well -- if you check for it and it is not set, the if condition won't be triggered. If you don't check for id and it is not set, it will attempt to check for id.indexOf(), and will throw an error because id is undefined.
@ObsidianAge He means you have a typo in your first example? am not sure
@ObsidianAge I mean you have an extra '&&' on your answer
Oh, I see. I did indeed. Was looking at the wrong one of the two examples ;) Well spotted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.