0

This is a follow up to my earlier question.

I wanted to compare the results I get back from filling out a form.

This is what I have so far:

const eqObj = (obj, source) =>
    Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);

$('#btn').on('click', function() {
    let $inputs = $('#new_form :input');
    let new_vals = {};
    $inputs.each(function() {
        new_form[this.id] = $(this).val();
    });

    console.log(new_vals);
    $.getJSON(api, function(data) {
        data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_vals, d.values){//open first models and append matched values}
            else {//open other modal}
        });
    });
});

My console.log() for new_vals: {start_date: "2019-12-25", end_date: "2020-04-15"}

my console.log() for d.values:

{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2020-01-01", end_date: "2020-03-15"}
{start_date: "2019-12-25", end_date: "2020-04-15"}
{start_date: "2020-03-20", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2019-10-01", end_date: "2020-03-31"}
{start_date: "2020-01-01", end_date: "2020-01-31"}
{start_date: "2020-01-19", end_date: "2020-01-25"}

When I enter the unmatched values, I am able to open the second modal as I want, but when I enter the matched value in my form, it opens both modals.

Why are both modals opening in my if statement? Is there any way I just do the $.getJSON() in my if statement? I don't need it? I only need the $.getJson() if there are matches, if not I need to open another modal.

nb_nb_nb
  • 1,243
  • 11
  • 36
  • The code here has several different variables for what appears to be the same thing (it's hard to tell). `new_vals`, `new_form`, and `new_run_vals` are all present in the click event handler; which is the one that you want to contain the values of your form? – Heretic Monkey May 28 '20 at 20:06
  • I have fixed that. Sorry about that. – nb_nb_nb May 28 '20 at 20:07

1 Answers1

0

You probably need to improve your if statement. If you want to show one or another modal only and never both you need to return as soon as the match happens. Try this:

       data.forEach(d => {
            console.log(d.values);
            if (eqObj(new_run_vals, d.values) {
              //open first models and append matched values;
              return;
            }
            //open other modal
        });
ELO
  • 19
  • 4