1

I am trying to build a simple 'blog' that myself or a moderator can remove by calling a delete function. However, I only want the delete button to show for administrators. I created a function to validate the user, that is working fine. However, I am not familiar enough with Javascript to know whether to use window.onload or onopen or onchange, or how to attach the function to my Foreach loop to run for each blog post I have. When I have 10 blog posts, it only shows for the first (or last) post.

I have tried adding the "onload / onopen / onchange" commands to the body, to the foreach loop, and to my tags to see if it responds differently.

<script>
    function ShowDelete()
{
    var x = document.getElementById("Delete");
        if (userid === "1") {
            x.style.display="block";
    }
    else {
        x.style.display="none";
    }
}
window.onload = ShowDelete;
</script>
<?php foreach ($entries as $entry) : ?>
  <?php if ($userid == 1) { ?>
<input type="submit" id="btnDelete" value="Delete Post" />
<?php } ?>
<?php endforeach; ?>

Ok Thank you all so much for the responses, I simply input the decision statement inside the loop to determine whether to show or skip. Thanks a ton!!!

3
  • 2
    Elements need to have unique ID attributes also userid in your JS looks like it is undefined? Commented Apr 27, 2019 at 3:00
  • There is no onload for an input Commented Apr 27, 2019 at 3:36
  • Add a class for your <input/> elements that is determined by your userid to modify the style Commented Apr 27, 2019 at 4:46

2 Answers 2

1

You are creating an HTML input and then hiding it. Best practice is not to create the element in the first place based on your userid.

<?php foreach ($entries as $entry) : ?>
    /* Check for userid here and create delete element if condition is met */
<?php endforeach; ?>
Sign up to request clarification or add additional context in comments.

Comments

0

No need to call a function multiple times to set the style. In your onload event, capture all of the <input/> elements by class name and set your display style. Note that the id attribute must be unique, so the class attribute should be used instead of id.

const userid = "0";
window.addEventListener('DOMContentLoaded', () => {
  let inputs = document.getElementsByClassName("Delete");
  Array.from(inputs).forEach(input => {
    input.style.display = userid === "1" ? "block" : "none";
  });
});
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />

It may also be of benefit to take a look at this post regarding load listeners.

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.