If compared values are true then $.getJSON()

回眸只為那壹抹淺笑 提交于 2020-06-16 23:51:56

问题


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.


回答1:


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
        });


来源:https://stackoverflow.com/questions/62073555/if-compared-values-are-true-then-getjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!