0

I have written a code which works on change but now I am also looking into page load and anything happens on the input field which has that specific class like blur or oninput ot paste or whatever, it should trigger the code and the moment the value is more than 0.00, it should run the code and display the label to block

Here is my code

  document.addEventListener('readystatechange', function(e) {
    switch (e.target.readyState) {
      case "complete":
        $('.totalsTeal').trigger('change');
        break;
      }
    });

and here is how the change event is written

  $(document).on('change focus blur', '.totalsTeal', function() {
    let self = $(this);
    let day = self.attr('data-name');
    if (self.val() === "0.00") {
      $('#w1_' + day).parent().find('label').css('display', 'none');
    } else {
      $('#w1_' + day).parent().find('label').css('display', 'block');
    }
});

the above code shows what I have done and what I am trying to write

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Dunn
  • 11
  • 1

2 Answers2

0

Use the input event, which triggers when an input field receives any input.

This is really a trivial operation that really isn't made that much simpler with JQuery. Also, you should be using CSS classes instead of working with inline styles as inline styles are more difficult to override and can lead to duplication of code.

Place the following code within a <script> element and place that element just prior to the closing body tag and you're done.

// Get a reference to the element where the message will be
// FYI: A label is not meant for this.
const output = document.querySelector(".hidden");

// Set up an input event handler on the input field
// The event will trigger as any kind of input happens to the field
document.querySelector(".foo").addEventListener("input", function(e) {
  // All values that come from HTML are strings.
  // Prepending that string with + implicitly converts it to a number
  if(+this.value > 0){
     // Remove the hidden CSS class to reveal element
     output.classList.remove("hidden");
  } else {
     // Apply the hidden CSS class to hide the element
     output.classList.add("hidden");
  }
});
/* When possible, use CSS classes instead of  inline styles. */
.hidden { display:none; }
<input class="foo" type="number">
<div class="hidden">Message Here</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • thanks, but the code does not match what i have written, can you actually modify my code to display me what it should look like – Dunn Jul 20 '23 at 15:37
  • @Dunn Not sure what you mean. Your code is wrong. My code is right. What is the problem? – Scott Marcus Jul 20 '23 at 15:38
  • @Dunn Please explain how my code doesn't accomplish what you are after? Your code has excessive statements and uses a `label` element incorrectly. – Scott Marcus Jul 20 '23 at 15:49
  • @ScottMarcus See my answer. It uses the labels, IDs and classes OP is using. It would have been easier for us if we had the matching HTML but at least I tried – mplungjan Jul 20 '23 at 15:56
0

Please be consistent - use plain JS OR jQuery, please do not mix.

jQuery

$(function() {
  $('.totalsTeal').on('input', function() {
    console.log(this.value, this.value === '0.00')
    const day = $(this).data('name');
    $('#w1_' + day).closest('.parentDiv').find('label')
      .toggle(+$(this).val() !== 0)
  }).trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="parentDiv">
  <input class="totalsTeal" type="number" value="1.00" data-name="x">
  <span id="w1_x">Not sure what wl is</span>
  <label hidden>Whatever the label is - I cannot tell until you post some HTML</label>
</div>
<div class="parentDiv">
  <input class="totalsTeal" type="number" value="0.00" data-name="y">
  <span id="w1_y">Not sure what wl is</span>
  <label  hidden>Message Here</label>
</div>
<div class="parentDiv">
  <input class="totalsTeal" type="number" value="1.00" data-name="z">
  <span id="w1_z">Not sure what wl is</span>
  <label  hidden>Message Here</label>
</div>

Vanilla JS

window.addEventListener('DOMContentLoaded', () => {
  const container = document.getElementById('container')
  container.addEventListener('input', (e) => {
    const tgt = e.target.closest('.totalsTeal'); // in case it has children
    if (!tgt) return; // not a .totalsTeal or child thereof
    const day = tgt.dataset.name;
    console.log(day,`w1_${day}`)
    document.getElementById(`w1_${day}`).closest('div').querySelector('label').hidden = +tgt.value !== 0;
  });
  container.querySelectorAll('.totalsTeal').forEach(inp => {
    console.log(inp.value)
    inp.dispatchEvent(new Event('input', {
      bubbles: true,
      cancelable: true
    }));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div id="container">
  <div class="parentDiv">
    <input class="totalsTeal" type="number" value="0.00" data-name="x">
    <span id="w1_x">Not sure what wl is</span>
    <label hidden>Message Here</label>
  </div>
  <div class="parentDiv">
    <input class="totalsTeal" type="number" value="1.00" data-name="y">
    <span id="w1_y">Not sure what w1 is</span>
    <label hidden>Message Here</label>
  </div>
  <div class="parentDiv">
    <input class="totalsTeal" type="number" value="2.00" data-name="z">
    <span id="w1_z">Not sure what w1 is</span>
    <label hidden>Message Here</label>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • However the use of `label` here is incorrect. – Scott Marcus Jul 20 '23 at 15:40
  • its false in all cases even in 0 or 8 – Dunn Jul 20 '23 at 15:45
  • @ScottMarcus I need to see the HTML. The label is toggled regardless – mplungjan Jul 20 '23 at 15:59
  • @Dunn Please post example HTML and I will fix my scripts to match – mplungjan Jul 20 '23 at 16:00
  • 1
    `$('#w1_' + day).parent().find('label')` is future-bug prone. Use rather something more flexible like `$('#w1_' + day).closest(".parentDiv").find('label')` or rather use the input's ID and the `for` attribute of Labe... oh, wait, detached ` – Roko C. Buljan Jul 20 '23 at 16:08
  • *"use DOM OR jQuery, please do not mix"* - jQuery *uses* the DOM, pretty heavily. This statement is a bit misleading. You meant: "*jQuery's DOM ready*"? Or "plain JavaScript"? – Roko C. Buljan Jul 20 '23 at 16:16
  • `if (!tgt.matches('.totalsTeal')) return;` is a bug prone way to learn Event delegation. Works perfectly fine in the case of `input` or other action elements that semantically do not accept any child elements, but once users get a grasp on that wrong implementation it's difficult to change habit - or confusing at best. Read more here: https://stackoverflow.com/a/14533243/383904 – Roko C. Buljan Jul 20 '23 at 16:20
  • is `hidden` a class which has display set to none? – Dunn Jul 20 '23 at 17:03
  • No, hidden is an attribute true or false/removed – mplungjan Jul 20 '23 at 18:06
  • @RokoC.Buljan True, I use closest when there may be children. Updated – mplungjan Jul 20 '23 at 18:09
  • @RokoC.Buljan I did not bother with the correctness of the label since I have NOT idea of how OP has them organised. It is irrelevant until I know. – mplungjan Jul 20 '23 at 18:11
  • 1
    @mplungjan indeed OP missed a good bunch of [mcve] :) – Roko C. Buljan Jul 20 '23 at 18:15
  • its not working, i think its because the input field has a read only attribute or what but its not working as expected, it works only on page load., the input event but not on changing values – Dunn Aug 01 '23 at 19:55
  • You cannot have the read only field trigger without monitoring it. Instead trigger the change event where you change the value – mplungjan Aug 01 '23 at 20:11