Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  186] [ 1]  / answers: 1 / hits: 30226  / 7 Years ago, fri, june 9, 2017, 12:00:00
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)


More From » jquery

 Answers
15

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! :)


[#57515] Wednesday, June 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacied

Total Points: 124
Total Questions: 84
Total Answers: 98

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;