0

I'm practicing with a script developed by the user @Bibberty, where there are buttons that count clicks, divs are cloned and also sume input values and all run under LocalStorage, and everything works very well, but practicing with JS (I'm novice, level 0), I can not add a new function

My interest is to show a div (#regalo), only if the input #total has a value between 999 and 1,500.

This only works if I place values, but it does not work in auto mode...

SEE LIVE DEMO (jsfiddle, the snippet does not run here)

Any idea...?

Thanks in advance!

//----------------

SCRIPT:

$(document).ready(function(){
    if($('#total').val() > 999 ) {
         $('#regalo').show();
    }
    $('#total').on('change',function(){
        if($(this).val() > 999 ) {
            $('#regalo').show();
        }
        else{
            $('#regalo').hide();
        }
    })
})
3
  • Do you mean the value of the input-value of the shown item? Or the count itself or how many items are shown? Commented Apr 23, 2019 at 21:20
  • Hi k3lly.dev If you run the fiddle, you, when cloning, you will see an input called #total. From that input I want to take the value to show (or not) the div #regalo Commented Apr 23, 2019 at 21:27
  • I posted an answer @pablo_web, I tried to explain it as clear as possible. Hope it helps with your issue! Commented Apr 23, 2019 at 22:05

3 Answers 3

2

add this

$('.comp-clone').on('click',function(){
    if($('#total').val() > 999) {
        $('#regalo').show();
    }
    else{
        $('#regalo').hide();
    }
})

You arent checking if the input field changes you are checking if you change it

$(document).ready(function(){
    if($('#total').val() > 999 ) {
         $('#regalo').show();
    }
    $('#total').on('change',function(){
        if($(this).val() > 999 ) {
            $('#regalo').show();
        }
        else{
            $('#regalo').hide();
        }
    })
    $('.comp-clone').on('click',function(){
        if($('#total').val() > 999) {
            $('#regalo').show();
        }
        else{
            $('#regalo').hide();
        }
    })
})

That should work for you but if you wanted to clean that up a little

$(document).ready(function() {
    CheckTotal();
    $('#total').on('change', function () {
        CheckTotal();
    })
    $('.comp-clone').on('click', function () {
        CheckTotal();
    })
})

CheckTotal() {
    if ($('#total').val() > 999) {
        $('#regalo').show();
    }
    else {
        $('#regalo').hide();
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Hi zach. Sorry for not knowing, but ... add it where...? In the main script (on jsfiddle), or directly replace all my script posted here, by yours...?
No problem. It just needs to be added right under you other functions. I added the complete answer above
zach Thanks, I did not understand it. But it does not work. If you type the numbers with your keyboard, yes, ok, but it is what I also mention in my publication, it does not do it in automatic mode. Please, see here jsfiddle.net/9Lgvcf71/1
What do you mean automatic mode? i thought it just wasn't working when when you used the clone buttons
zach That is (for me) auto mode, hahaha. When you clone div´s, the input #total show the sum of values. What I want is that when the value of the input #total passes from 999 it shows the div #regalo, and when it exceeds the 1,500, it is again display=none ...
1
$(document).ready(function(){
  function manageRegalo() {
    const total = Number($("#total").val().replace(".",""));
    // or:
    //const total = suma();
    if(total > 999 && total < 1500) {
      $('#regalo').show();
    }
    else{
      $('#regalo').hide();
    }
  }

  $(document).on('click', function (event) {
      const target = event.target;
      if (target.matches('.comp-clone') || target.matches('.bbp')) {
        manageRegalo();
      }
    });
  manageRegalo();
});

JSFiddle

There are a couple of changes here:

  1. Don't use display: none to hide it, that way jQuerys show() will not work. Instead call hide() immediately, that's way I call manageRegalo() at the very end directly one time. If the split second that you can see the regalo at the beginning is a problem, add another CSS class to the element which includes display: none and use jQuerys .addClass() and .removeClass() to show and hide the regalo.
  2. $('#total').val() gives you a string value, you need to convert it to a number, but this string value can has dots in it, so the value 1.000 would be converted to 1, that's why we first need to remove all the dots. Another way to get the click would be to use the suma() function which is defined in the other JS-Code (inside the HTML-Window), but that one recalculates the value again.
  3. You checked if the value is greater than 999, but not if it is smaller than 1500.
  4. Don't listen at the total-Element for a click, first you don't click on the total-Element: You click on one of the Clone N Elements or on the red Xs. But don't listen on those directly as well, because the JS code that's already there inside the HTML code is listening on the document itself. If you would listen on the Clone N or Xs element, you would get the click event first, but at that time the total isn't calculated yet, so you would get the value always one click late.

1 Comment

Thanks!, 0xnoob. A very efficient, friendly, clean and tidy solution. I will study your recommendations thoroughly. Cheers!
1

I reviewed the code you posted and you have two major issues.

Never try adding more code without understanding the code already written.

It's a common thing that we start writing some code before even understanding the whole code already written, and this is a big problem since it could cause the other code to not work. I'll give you the example with your issue. Something that is preventing your code to give you the result you are expecting is that in the code previously written, the function that assings the valute to the input with id of total is converting the input to a string with String.toLocaleString() which converts totally the variable type from integer (which is what your are looking for) to a string.

Here is where this happens in the code:

const displaySuma=()=>document.getElementById("total").value=suma().toLocaleString("es-ES");

const suma = function() {
  return Array.from(document.querySelectorAll(".derecha div .add-prod"))
    .reduce((a, v) => a + parseFloat(v.value), 0);
}

So, to achieve the functionality you want, you need to remove the last function attached to the sum() function. It will be like this:

const displaySuma=()=>document.getElementById("total").value=suma();

Also, there's no need to add extra event listeners to your mini-app. Like I said, just try to give it a little of research before writing more code, if you do this, you'll be writing JavaScript code easily and understand how it works by the time you achieved your goal of modifying an already written piece of code.

There is already an event listening for the value in the code.

Since the script already has an event listening for the #total value change, we can just create a function and check the condition there. Here is the event listening:

document.addEventListener('click', (event) => {
  let target = event.target;
  // Add
  if (target.matches('.comp-clone')) {
    addClick();
    addToDerecha(event.target.dataset.clone);
    verifyCondition(); //We add our own function that we just made to verify the value.
  }
  // Remove
  if (target.matches('.bbp')) {
    removeClick();
    getParent('.derecha', target).removeChild(target.parentNode);
    storeHTML();
    displaySuma();
  }
});

And now, our function would simply be: (Vanilla JavaScript)

const verifyCondition = () =>{
    let total = Number(document.querySelector("#total").value);
    //We convert the value to integer anyways to prevent any kind of errors.
    if( 999 < total && total < 1200 ){//Check if value is between 999 and 1200
        document.getElementById("regalo").style="display:block;";
    }else{
        document.getElementById("regalo").style="display:none;";
    }
}

And that's it! Here is a fiddle with the new working code, try to give it a check and make sure to search for what you don't understand. That's how any Senior Developer started.

https://jsfiddle.net/ax0L12j7/

1 Comment

Thanks, k3lly.dev. It's another option, but I've lost the decimal point in the input #total, and there's no LocalStorage anymore. Down here @0xnoob has solved the problem for me. Thank you very much to both. I try to learn and here they help me a lot. True ;) ...

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.