-3

For each data.row 1,2,3,4 that is equal to > i want to add class to that specific element.

For example, if data.row1 is equal to > i want to add style to row1. How is that possible with a more efficient way? This is mainly for code reduction and optimization since my code consists of more than 20 lines doing the same thing.

Just a small note, data.row is a variable that comes from php with Json Encode.

 if(data.row1 === ">"){ $("#row1").addClass("Green");}

 if(data.row2 === ">") {$("#row2").addClass(Green);}

 if(data.row3 === ">"){ $("#row3").addClass(Green);}

 if(data.row4 === ">") {$("#row4").addClass(Green);}
Gragas Incoming
  • 825
  • 1
  • 9
  • 23

1 Answers1

1

How about a loop?

for(var i = 1; i < 5; i++)
  if(data['row'+i] === ">")
    $("#row"+i).addClass("Green");
finw3
  • 479
  • 5
  • 9
  • @mplungjan i am sorry but i have tried your code and it doesn't work – Gragas Incoming Mar 09 '18 at 18:26
  • Yes it does, You are doing it wrong or are not telling us the complete truth, The code above here should would and is what I meant with my comment – mplungjan Mar 09 '18 at 18:28
  • @mplungjan your idea is correct, but you never explain that you are using a loop. It may look obvious for an intermedian/advance coder, but maybe not for beginners. – finw3 Mar 09 '18 at 18:29
  • Seriously impossible to code PHP that returns a data object and never having heard of a loop – mplungjan Mar 09 '18 at 18:31
  • @mplungjan i dont have your experience i am a student. Of course i heared but i didnt know how to implement that. I tried with jquery `.each` at the start. Thanks for your help anyway – Gragas Incoming Mar 09 '18 at 18:35
  • @mplungjan Maybe he didn't code that part. I don't know man. What it is obvious for some people is not for others. For me it was obvious write the full loop, for you it wasn't. – finw3 Mar 09 '18 at 18:36
  • Apologies for doubting your lack of knowledge. – mplungjan Mar 09 '18 at 18:42
  • Knowledge is meaningless without practise – Gragas Incoming Mar 09 '18 at 18:44
  • You can use $.each([1,2,3,4]... or even `$("[id^=row]").each(function(i) { $(this).toggleClass("Green",data['row'+(i+1)] === ">"); });` – mplungjan Mar 09 '18 at 18:47
  • are you showing off right now? :) I feel so noob. Thanks again for the help – Gragas Incoming Mar 09 '18 at 18:49
  • @mplungjan can you answer this? It is similar to this question but more advanced :) https://stackoverflow.com/questions/49206723/pushing-arrays-based-on-each-row-input-dynamically – Gragas Incoming Mar 10 '18 at 07:58