Avoid accumulation in a string by repeatedly clicking on a button

Asked

Viewed 43 times

0

I have the following code that works as follows:

Clicking on the button returns a string aaaa,bbbbb which are the values of inputs.

Clicking for the second time returns aaaa,bbbbb,aaaa,bbbbb and so on.

The question: how to always return aaaa,bbbbb regardless of how many clicks are given

var strTotal2 ="";
$(document).ready(function(){
    $("#bsubmit").click(function(){
        $("input[class^='outro-form-control']").each(function(){
            var str2 = ($(this).val());
            strTotal2 = strTotal2+","+str2;
        });
        myString2 = strTotal2.substring(1);
        console.log(myString2);
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="sheets" name="sheets" class="contact-form row" method="post" action="c_form/envia.php" onsubmit="return false">
<input id="nome" name="nome" value="aaaa" class="outro-form-control" placeholder="Insira seu nome">
<input id="nation" name="email" value="bbbbb"  class="outro-form-control">
<button type="submit" id="bsubmit" value="Submit" name="submit" class="btn btn-success pull-right">Enviar</button>
<form>

  • 3

    var strTotal2 =""; must be inside the submit

1 answer

1


The whole question deserves an answer and will be the one from the Isac comment.

var strTotal2 =""; must be inside Submit.

$(document).ready(function(){
    $("#bsubmit").click(function(){
        var strTotal2 ="";
        $("input[class^='outro-form-control']").each(function(){
            var str2 = ($(this).val());
            strTotal2 = strTotal2+","+str2;
        });
        myString2 = strTotal2.substring(1);
        console.log(myString2);
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sheets" name="sheets" class="contact-form row" method="post" action="c_form/envia.php" onsubmit="return false">
<input id="nome" name="nome" value="aaaa" class="outro-form-control" placeholder="Insira seu nome">
<input id="nation" name="email" value="bbbbb"  class="outro-form-control">
<button type="submit" id="bsubmit" value="Submit" name="submit" class="btn btn-success pull-right">Enviar</button>
<form>

Browser other questions tagged

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