Pawan
Pawan

Reputation: 32331

How to avoid adding of button multiple times which was created dynamically

I have a requirement where I need to show a button labeled Set only when both the text in two Text input fields are the same. I am able to show the button Set which is created dynamically When clicked on the Validate button .

The Only issue i am seeing is that , the Set button is being added multiple times when ever if clicked on the Validate button

$(function () {
    $("#setcategory").hide();
    $(document).on('click', '#validate', function (event) {
        var val1 = $("#fort1text").val();
        var val2 = $("#fort2text").val();
        if (val1 != '' && val2 != '') {
            if (val1 == val2) {
                var setthiscategory = '<input type="button" id="setthiscategory" class="saveclassbtn btn blue" id="sett1cat" value="Set This Category"/>';

                $("#validate").after(setthiscategory);

            } else {

            }
        }
    });

});

Please let me know how to resolve this ??

Thanks in advance .

Upvotes: 0

Views: 27

Answers (3)

geevee
geevee

Reputation: 5461

just add an if statement to verify that you perform the action only if #setthiscategory doesn't exist:

if (!$('#setthiscategory').length)
    $( "#validate" ).after(setthiscategory);

hope that helps.

Upvotes: 0

Sarath Kumar
Sarath Kumar

Reputation: 2353

try this..

<input type="text" id="fort1text" class="m-wrap span12" placeholder="">
    <input type="text" id="fort2text" class="m-wrap span12" placeholder="">
    <input type="button" id="validate" value="Validate">
    <script>

        $(function () {
            $("#setcategory").hide();
        });
        $(document).on('click', '#validate', function (event) { 
            var val1 = $("#fort1text").val();
            var val2 = $("#fort2text").val();
            if(val1!=''&&val2!='')
            {
            if(val1==val2)
            {  
        var setthiscategory = '<input type="button" id="setthiscategory" class="saveclassbtn btn blue" id="sett1cat" value="Set This Category"/>';
              if($("#setthiscategory").length==0)
                $( "#validate" ).after(setthiscategory);
            }
            else
            {
               $('#setthiscategory').remove();
            }
            }
        });

    </script>

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

use length in jquery ,to find that element was created or not

if($("#setthiscategory").length==0){
      $( "#validate" ).after(setthiscategory);
}

Upvotes: 1

Related Questions