Home > Mobile >  I am repeating a lot of code. Is there a way I can reuse that same code with out having to copy it a
I am repeating a lot of code. Is there a way I can reuse that same code with out having to copy it a

Time:06-05

I am making a question and answer webpage. The user selects the topic, then a lesson from that topic, and number of questions to show. The questions are selected from an array. I have made different arrays for different topics, then for each object in the array I have given it the property of lesson, question and answer. After user submits there request, questions are selected from the appropriate array based on the lesson selected by user, and that is put into another array and shuffled. Questions from this is then displayed in the divs. I have written the code that extracts the questions based on user selected lessons and then shuffling them and displaying them in the html page several times (for each topic). eventually I want to expand my topics and this would mean I would be copying and pasting almost the same code again and again. Is there a way I don't need to keep repeating this part?

HTML

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3 Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <div >
    <label for="myTopic">Topic:</label>
    <select id="myTopic">
      <option value="">--Select--</option>
      <option value="Biology">Biology</option>
      <option value="Chemistry">Chemistry</option>
      <option value="Physics">Physics</option>
    </select>


      <select id='myBiology' >
      <option value="">--Select Lesson--</option>
      <option value="Cells">Cells</option>
      <option value="Tissues and organs">Tissues and organs</option>
      <option value="Cell division">Cell division</option>
      </select>

      <select id='myChemistry' >
      <option value="">--Select Lesson--</option>
      <option value="Atoms, elements and compounds">Atoms, elements and compounds</option>
      <option value="Periodic table">Periodic table</option>
      <option value="Bonding">Bonding</option>
      </select>

      <select id='myPhysics' >
      <option value="">--Select Lesson--</option>
      <option value="Forces and motion">Forces and motion</option>
      <option value="Energy stores and transfer">Energy stores and transfer</option>
      <option value="Electricity">Electricity</option>
      </select>


    <label for="myNumber">Number of Questions:</label>
    <select id='myNumber'>
    <option value="">--Select--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="5">5</option>
    <option value="10">10</option>
    </select>


    <button  type="submit">Go</button>
  </div>

  <div  id="q1"></div>
  <div  id="q2"></div>
  <div  id="q3"></div>
  <div  id="q4"></div>
  <div  id="q5"></div>
  <div  id="q6"></div>
  <div  id="q7"></div>
  <div  id="q8"></div>
  <div  id="q9"></div>
  <div  id="q10"></div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="mainjs.js" charset="utf-8"></script>
</body>

</html>

JS


    var biologyQ=[{
        "lesson": "Cells",
        "difficulty": "1",
        "question": "This is q1 for Cells",
        "answer": "This is a1 for Cells"
      },
      {
        "lesson": "Cells",
        "difficulty": "1",
        "question": "This is q2 for Cells",
        "answer": "This is a2 for Cells"
        },
        {
          "lesson": "Cells",
          "difficulty": "2",
          "question": "This is q3 for Cells",
          "answer": "This is a3 for Cells"
        },
      {
        "lesson": "Tissues and organs",
        "difficulty": "1",
        "question": "This is q1 for Tissues and organs",
        "answer": "This is a1 for Tissues and organs"
      }, {
        "lesson": "Tissues and organs",
        "difficulty": "2",
        "question": "This is q2 for Tissues and organs",
        "answer": "This is a2 for Tissues and organs"
      },
      {
        "lesson": "Tissues and organs",
        "difficulty": "2",
        "question": "This is q3 for Tissues and organs",
        "answer": "This is a3 for Tissues and organs"
      }, {
        "lesson": "Cell division",
        "difficulty": "1",
        "question": "This is q1 for Cell division",
        "answer": "This is a1 for Cell division"
      },
      {
        "lesson": "Cell division",
        "difficulty": "2",
        "question": "This is q2 for Cell division",
        "answer": "This is a2 for Cell division"
        },
        {
          "lesson": "Cell division",
          "difficulty": "3",
          "question": "This is q3 for Cell division",
          "answer": "This is a3 for Cell division"
      }
    ];
    
    var chemistryQ=[{
        "lesson": "Atoms, elements and compounds",
        "difficulty": "1",
        "question": "This is q1 for Atoms, elements and compounds",
        "answer": "This is a1 for Atoms, elements and compounds"
      },
      {
        "lesson": "Atoms, elements and compounds",
        "difficulty": "1",
        "question": "This is q2 for Atoms, elements and compounds",
        "answer": "This is a2 for Atoms, elements and compounds"
        },
        {
          "lesson": "Atoms, elements and compounds",
          "difficulty": "1",
          "question": "This is q3 for Atoms, elements and compounds",
          "answer": "This is a3 for Atoms, elements and compounds"
        },
      {
        "lesson": "Periodic table",
        "difficulty": "1",
        "question": "This is q1 for Periodic table",
        "answer": "This is a1 for Periodic table"
      }, {
        "lesson": "Periodic table",
        "difficulty": "2",
        "question": "This is q2 for Periodic table",
        "answer": "This is a2 for Periodic table"
      },
      {
        "lesson": "Periodic table",
        "difficulty": "3",
        "question": "This is q3 for Periodic table",
        "answer": "This is a3 for Periodic table"
      }, {
        "lesson": "Bonding",
        "difficulty": "1",
        "question": "This is q1 for Bonding",
        "answer": "This is a1 for Bonding"
      },
      {
        "lesson": "Bonding",
        "difficulty": "2",
        "question": "This is q2 for Bonding",
        "answer": "This is a2 for Bonding"
        },
        {
          "lesson": "Bonding",
          "difficulty": "3",
          "question": "This is q3 for Bonding",
          "answer": "This is a3 for Bonding"
      }
    ];
    
    var physicsQ=[{
        "lesson": "Forces and motion",
        "difficulty": "1",
        "question": "This is q1 for Forces and motion",
        "answer": "This is a1 for Forces and motion"
      },
      {
        "lesson": "Forces and motion",
        "difficulty": "1",
        "question": "This is q2 for Forces and motion",
        "answer": "This is a2 for Forces and motion"
        },
        {
          "lesson": "Forces and motion",
          "difficulty": "1",
          "question": "This is q3 for Forces and motion",
          "answer": "This is a3 for Forces and motion"
        },
      {
        "lesson": "Energy stores and transfer",
        "difficulty": "1",
        "question": "This is q1 for Energy stores and transfer",
        "answer": "This is a1 for Energy stores and transfer"
      }, {
        "lesson": "Energy stores and transfer",
        "difficulty": "2",
        "question": "This is q2 for Energy stores and transfer",
        "answer": "This is a2 for Energy stores and transfer"
      },
      {
        "lesson": "Energy stores and transfer",
        "difficulty": "3",
        "question": "This is q3 for Energy stores and transfer",
        "answer": "This is a3 for Energy stores and transfer"
      }, {
        "lesson": "Electricity",
        "difficulty": "1",
        "question": "This is q1 for Electricity",
        "answer": "This is a1 for Electricity"
      },
      {
        "lesson": "Electricity",
        "difficulty": "2",
        "question": "This is q2 for Electricity",
        "answer": "This is a2 for Electricity"
        },
        {
          "lesson": "Electricity",
          "difficulty": "3",
          "question": "This is q3 for Electricity",
          "answer": "This is a3 for Electricity"
      }
    ];
    
    $(document).ready(function(){
        $("#myTopic").change(function(){
            $(this).find("option:selected").each(function(){
              var optionValue = $(this).attr("value")
            $(".lesson-select").hide();
            $("#my"  optionValue).show();
            });
          });
        });
    
    
    $(document).ready(function(){
        $('.go-btn').on('click',
    
        function() {
          if ($('#myTopic').val() == 'Biology')
          {
            var array = biologyQ;
            const lessonSelected = $('#myBiology').val();
            var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
    
                 {
                    const array = lessonResult;
    
                    function shuffle(array) {
                      for (let i = array.length - 1; i > 0; i--) {
                        let j = Math.floor(Math.random() * (i   1));
                        let temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                      }
                    return array;
                    };
    
                    const result = shuffle(array);
                 $('#q1').html(result[0].question);
                 $('#q2').html(result[1].question);
                 $('#q3').html(result[2].question);
    
                   var currentVal = $('#myNumber').val();
                   $('.selected').hide().slice(0, currentVal).show();
                  }
          }
    
          else if ($('#myTopic').val() == 'Chemistry')
            {
              var array = chemistryQ;
              const lessonSelected = $('#myChemistry').val();
              var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
                   {
                      const array = lessonResult;
    
                      function shuffle(array) {
                        for (let i = array.length - 1; i > 0; i--) {
                          let j = Math.floor(Math.random() * (i   1));
                          let temp = array[i];
                          array[i] = array[j];
                          array[j] = temp;
                        }
                      return array;
                      };
    
                      const result = shuffle(array);
                   $('#q1').html(result[0].question);
                   $('#q2').html(result[1].question);
                   $('#q3').html(result[2].question);
    
                     var currentVal = $('#myNumber').val();
                     $('.selected').hide().slice(0, currentVal).show();
                    }
                  }
    
                  else if ($('#myTopic').val() == 'Physics')
                    {
                      var array = physicsQ;
                      const lessonSelected = $('#myPhysics').val();
                      var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });
                           {
                              const array = lessonResult;
    
                              function shuffle(array) {
                                for (let i = array.length - 1; i > 0; i--) {
                                  let j = Math.floor(Math.random() * (i   1));
                                  let temp = array[i];
                                  array[i] = array[j];
                                  array[j] = temp;
                                }
                              return array;
                              };
    
                              const result = shuffle(array);
                           $('#q1').html(result[0].question);
                           $('#q2').html(result[1].question);
                           $('#q3').html(result[2].question);
    
                             var currentVal = $('#myNumber').val();
                             $('.selected').hide().slice(0, currentVal).show();
                            }
                          }
    
        else
          {
            $(".selected").hide();
          }
    
          });
        });

css

   

    .selected{
        display:none
    }
    
    .lesson-select{
      display:none
    }

CodePudding user response:

You can simplify your code like below:

$(document).ready(function(){
    $('.go-btn').on('click',function() {

        var array = ($('#myTopic').val() == 'Biology' ? biologyQ : ($('#myTopic').val() == 'Chemistry' ? chemistryQ : physicsQ));
        const lessonSelected = ($('#myTopic').val() == 'Biology' ? $('#myBiology').val() : ($('#myTopic').val() == 'Chemistry' ? $('#myChemistry').val() : $('#myPhysics').val()));
        var lessonResult = $.grep(array, function(e){ return e.lesson == lessonSelected; });

        {
            const array = lessonResult;

            function shuffle(array) {
                for (let i = array.length - 1; i > 0; i--) {
                    let j = Math.floor(Math.random() * (i   1));
                    let temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
                return array;
            };

            const result = shuffle(array);
            $('#q1').html(result[0].question);
            $('#q2').html(result[1].question);
            $('#q3').html(result[2].question);

            var currentVal = $('#myNumber').val();
            $('.selected').hide().slice(0, currentVal).show();
        }
    });
});
  • Related