I
I
iiiideb2020-04-25 11:06:05
PHP
iiiideb, 2020-04-25 11:06:05

JS removal error?

Hello, such a problem: there is a function to hide a div block

function deleteAlert() {
  var x = document.getElementById("alert");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

It makes a div element with display: none on click;
in this html document:
<div class="container mt-5">
  @if($errors->any())
    @foreach($errors->all() as $error)
      <div class="alert alert-danger alert-dismissible fade show" id="alert" role="alert">
      {{ $error }}
      <button type="button" class="close" data-dismiss="alert" aria-label="Close" onclick="deleteAlert()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    @endforeach
  @endif
  @if(session('success'))
  <div class="alert alert-success alert-dismissible fade show" id="alert" role="alert">
  {{ session('success') }}
  <button type="button" class="close" data-dismiss="alert" aria-label="Close" onclick="deleteAlert()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
  @endif

@yield('content')
</div>

If 1 block is displayed (this is a block of errors), then everything works fine, but if 2 or more, then when you click on the close button, the first block closes, after clicking on the second, the first block appears, and the second does not disappear.
I don’t know and don’t understand anything in js, I only know that there is an error in the lines above

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-04-25
@iiiideb

<button type="button" class="close" aria-label="Close">...</button>

const alerts = document.querySelectorAll('.alert');

for (const alert of alerts) {
  const closeButton = alert.querySelector('.close');

  if (closeButton !== null) {
    closeButton.addEventListener('click', event => {
      event.preventDefault();

      alert.style.setProperty('display', 'none');
    });
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question