1

I want to get the same value on string after split

If I have the numbers (as a string): 1,6,18,2 and I use .includes I get an output which looks like this: 1,2,6,8,18

How can I get same with that string -> 1,2,6,18

This is my code in js :

trHTML = '';    
total = 20; 
var antrian = $('#antrian').val(); // 1,6,18,2

for(i = 1; i <= total; i++){
   if(antrian.includes(i)){
     trHTML += <button style="background-color: gray;"> '+ i +'</button>';
   } else {
     trHTML += <button style="background-color: red;"> '+ i +'</button>';  
   }
}

From that code I got button output button with number, if I consol.log(trHTML) the output is 1,2,6,18 but output in HTML is gray button 1,2,6,8,18 and others is red button

How can I got grey button with number 1,2,6,18 or same with console.log(trHTML) ?

Can someone help me or give me an example?

1 Answer 1

5

The reason why 8 is included in 1,6,18,2 is that there is an 8 in the string. One option is make antrian an array using split()

var trHTML = '';    //Add var
var total = 20;     //Add var
var antrian = $('#antrian').val().split(","); //Add split() - this will return to [1,6,18,2]

for(var i = 1; i <= total; i++){ //Add var on i
   if(antrian.includes(i.toString())){
     trHTML += '<button style="background-color: gray;"> '+ i +'</button>';
   } else {
     trHTML += '<button style="background-color: red;"> '+ i +'</button>';  
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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.