Insert input only if it does not yet exist

Asked

Viewed 255 times

2

I am working on a form with dynamically inserted fields. But I want the fields to be inserted only if they don’t exist yet. 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-receiver fieldset').append("<p>" +$(this).parent().text()+ "<input name='" + $(this).parent().text().toLowerCase() + "'></p>")
            }
        })
    });
</script>

So the insertion works perfectly. However, it is possible for repeated fields to be added if the user decides to mark more checkboxes and click the add button. Should be added only if there are no.

I tried it this way:

$('#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 hasn’t worked yet. Could someone help here? : D

3 answers

2


I solved your problem as follows, although I think to solve it differently.

I added to the checkbox an attibute data-add which will ensure whether the field has been inserted or not, stayed 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 follow the result in this DEMO

If you do not want to use attributes data- can do this way 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 follow the result also in this DEMO

  • Man!! Thanks a lot! I had not even considered this possibility! Solved my problem. Thank you very, very much! ;-)

  • 1

    Have @Pedrovinícius implement also the solution of the friend there referring to the names of the field, a great hug and good luck with the projects.

1

I would avoid using space names.
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 I 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: http://jsfiddle.net/ULLD9/2/

Somehow the only relevant difference between my code and yours is that I used if (!$('#form-receiver').find( .... ).length. The length is only for precaution but the find is to search for the element inside the form. I also changed to this.checked because you don’t need jQuery to do that check.

  • Thank you very much. Your reply was very useful! Could you explain to me what is happening there in the replace function? Just so I know exactly what I’m doing and ensure learning :-)

  • 1

    @Pedrovinícius, the idea of "Camelize" is to remove white spaces and make the first letter of each word stay in "Capital". That is to say: border-width stays borderWidth

  • Ahh yes. Thank you! D

1

In fact, although there is already a good answer, 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 method .has() jQuery does not return a boolean, and yes the result of a selection, then you would have to check if someone returned in the selector:

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

And I wouldn’t recommend creating tags name with white spaces, I would make a trim():

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

Track your solution in operation here.

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

  • 1

    But Trim does not only remove spaces before and after the string?

  • 1

    @Pedrovinícius, yes, but there were spaces after, the middle ones weren’t even quoting, but it’s also interesting to make a replace in all spaces. Good placement.

  • Ahh yes. I hadn’t even noticed the spaces after kkk Thanks so dear! Your reply was very helpful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.