0

I want to add a class active to the element go_back_right when both inputs with classes search_box_name and search_box_id have any value. I have tried referencing to the answers that are already on this platform, but I had no luck, as I'm new to js. Any help?

.go_back_right:active {
  background-color: rgba(255, 0, 0, 0.05);
  animation: status 4s ease forwards;
}
<div class="search_box_container">
  <input class="search_box_name" id="search_bar username" for="username" name="username" type="text">
  <input class="search_box_id" id="search_bar roomNamehtml" name="room" type="text">
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

3 Answers3

0

function setClass() {
  if (document.querySelector(".search_box_name").value != "" && document.querySelector(".search_box_id").value != "") {
    document.querySelector(".go_back_right").setActive();
  } else {
    document.querySelector(".go_back_right").setActive(false);
  }
}
setClass();
.go_back_right:active {
  background-color: rgba(255, 0, 0, 0.05);
  animation: status 4s ease forwards;
}
<div class="search_box_container">
  <input oninput="setClass()" class="search_box_name" id="search_bar username" for="username" name="username" type="text">
  <input oninput="setClass()" class="search_box_id" id="search_bar roomNamehtml" name="room" type="text">
</div>
Fakt309
  • 821
  • 5
  • 14
0

Below is jQuery snippet to set an event for adding/removing class

$(document).ready(function () {
    setEvents();
    $('.search_box_container').trigger('change');
});
function setEvents() {
    $('.search_box_container').on('change', function () {
        var $this = $(this),
            search_box_name = $this.find('.search_box_name').val().trim(),
            search_box_id = $this.find('.search_box_id').val().trim();
        if (search_box_name && search_box_id) {
            $('.go_back_right').addClass('active');
        } else {
            $('.go_back_right').removeClass('active');
        }
    });
}
Wazeed
  • 1,230
  • 1
  • 8
  • 9
0

I think you want to add an additional class to the element with the class .go_back_right right? If so, add this to your JS file:

const searchBoxName = document.getElementByClassName('search_box_name');
const searchBoxId = document.getElementByClassName('search_box_id');
const goBackRight = document.getElementByClassName('.go_back_right');

const addClass = () => {
  if (searchBoxName && searchBoxName.value && searchBoxId && searchBoxId.value) {
    goBackRight.classList.add('active');
  }
}

addClass()

Read this, this and this for more info and btw, you can't have two or more elements having the same id like that search_bar id you have on both your inputs.