-1

I understand that we can pre-fill some data in an HTML form using the URL. For example, www.example.com/?itemname=sth

While this time I would like to perform a click action through the URL for my filter to work. I have written the following code to click the checkbox but it doesn't work, May I know how to fix it? Thanks.

Thank you guys I have tried by simply checked the checkbox and it works but due to my filter needs a click action to trigger so that's why i would like to do it with a click!

<label class="form-check-label">
      <input type="checkbox" class="form-check-input product_check" id="Tutor_subject_1" name="Maths" value="Maths">Maths<br>
       <?php if (isset($_GET['itemname']) && $_GET['itemname'] === 'sth' ): ?> 
           <script>document.getElementsByName("Maths").click();</script>
       <?php endif; ?>
</label>

sevenine
  • 19
  • 6
  • It's `getElementsByName` not `getElementByName`. See https://stackoverflow.com/questions/2980830/javascript-getelementbyname-doesnt-work – j08691 Sep 14 '20 at 15:45
  • Hi @j08691, I have fixed the spelling mistakes and tried it with – sevenine Sep 14 '20 at 15:48
  • 1
    Well you don't seem to have read the link in my comment. `getElementsByName` returns a nodelist so you need to specify which element you need, e.g. `[0]`. Also, make sure to check the browser tools console when debugging JavaScript – j08691 Sep 14 '20 at 15:49
  • Could this be that javascript runs on the browser but PHP only runs on the server issue – RiggsFolly Sep 14 '20 at 15:49
  • Doing that in js makes little sense. Also would be simpler to set the `checked` attribute, not try and programatically click the box – RiggsFolly Sep 14 '20 at 15:53
  • What have you tried to debug the problem? Usually, this is **either** a PHP problem, **or** a Javascript problem – Nico Haase Sep 14 '20 at 15:56

1 Answers1

3

There obviously no need for javascript, just add checked attribute with php:

<input 
    type="checkbox" 
    class="form-check-input product_check" 
    id="Tutor_subject_1" 
    name="Maths" 
    value="Maths"
    <?= (isset($_GET['itemname']) && $_GET['itemname'] === 'sth') ? ' checked' : '' ?>
>Maths<br>
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • 3
    Not sure why someone would downvote this as it seems perfectly reasonable. I'd avoid the PHP shorttag though and use `echo` – j08691 Sep 14 '20 at 15:50