Insert input only if it does not already exist

2

I'm working on a form with dynamically inserted fields. But I want fields to be inserted only if they do not already exist. My html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
   <meta charset="utf-8">
   <title>Testando</title>
</head>

<body>
    <p>Milho <input type="checkbox" class="check"> </p>
    <p>Sorgo <input type="checkbox" class="check"> </p>
    <p>Monenzina <input type="checkbox" class="check"> </p>
    <p>Calcário Calcítico <input type="checkbox" class="check"> </p>
    <p>Farelo de Soja <input type="checkbox" class="check"> </p>
    <p>Farelo de Algodão <input type="checkbox" class="check"> </p>
    <p>Aromatizante <input type="checkbox" class="check"> </p>
    <p>Farelo de Arroz <input type="checkbox" class="check"> </p>

    <button id="add-button" type="submit">Adicionar</button>

    <div id="receiver">
        <form id="form-receiver">
            <fieldset>

            </fieldset>
        </form>
    </div>
</body>

My javascript:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>$('#add-button').click(function(){$('.check').each(function(){if($(this).is(':checked')){$('#form-receiverfieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
            }
        })
    });
</script>

So the insert works perfectly. However, it is possible that repeated fields are added if the user decides to mark more checkboxes and click the add button. They should be added only if they do not exist.

I tried the following:

$('#add-button').click(function(){
        $('.check').each(function(){
            if($(this).is(':checked')){
                if(!$('#form-receiver').has("input[name='" $(this).parent().text().toLowerCase() "']"){
                    $('#form-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
                }
            }
        })
    });

But it still did not work. Could someone help here? : D

    
asked by anonymous 14.07.2014 / 15:52

3 answers

2

I solved your problem the following way, although I think that to resolve otherwise.

I added to checkbox an attibuto data-add that will guarantee if the field was inserted or not, it was this way.

JQuery

$(function(){
    $('#add-button').click(function(){
            $('.check').each(function(){
                if($(this).is(':checked'))
                    if(!$(this).data('add')) {
                        $('#form-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>");
                        $(this).attr('data-add', true);
                    }
            });
        });
});

You can track the result in DEMO

If you do not want to use attributes data- you can do this using a variable to control it.

var checked = [];

$(function(){
    $('#add-button').click(function(){
            $('.check').each(function(index){
                if($(this).is(':checked'))
                    if(!checked[index]) {
                        $('#form-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>");
                        checked[index] = true;
                    }
            });
        });
});

You can track the result also in this DEMO     

14.07.2014 / 16:02
1

In fact, although there are already good answers, the error in its solution and lack of concatenation in the check selector:

// adicionei os operadores de concatenação de string '+'
if(!$('#form-receiver').has("input[name='" + $(this).parent().text().toLowerCase() + "']")

And also the .has() method of jQuery does not return a boolean , but the result of a selection, so you would have to check if someone returned the selector:

$('#form-receiver fieldset').has("input[name='" + $(this).parent().text().toLowerCase().trim() + "']").length == 0

And I would not recommend creating tags name with whitespace, I'd make a trim() :

$(this).parent().text().toLowerCase().trim();

Track your working solution here .

But I still recommend using the @Diego Vieira solution for being cleaner.

    
14.07.2014 / 16:21
1

I would avoid using names with spaces. So I suggest a function to make CamelCase source here :

function camelCase(input) {
    return input.toLowerCase().replace(/[-\s](.)/g, function (match, group1) {
        return group1.toUpperCase();
    });
}

Then you could use this code:

$('#add-button').click(function () {
    $('.check').each(function () {
        if (this.checked) {
            var nome = $(this).parent().text();
            if (!$('#form-receiver').find("input[name='" + camelCase(nome) + "']").length) {
                $('#form-receiver fieldset').append("<p>" + nome + "<input name='" + camelCase(nome) + "'></p>")
            }
        }
    })
});

Example: link

In what way the only relevant difference between my code and yours is that I used it   if (!$('#form-receiver').find( .... ).length . The length is only as a precaution, but the find is to look for the element within the form. I also changed to this.checked because you do not need jQuery to do this check.

    
14.07.2014 / 16:10