How to use two forms with the same ID?

Asked

Viewed 603 times

1

Hello,

I found a problem. I’m integrating an HTML form with Google Sheets. The point is that I have two forms, I’m not excellent in Javascript but it seems that the "var Fields" function works only with the HTML id. Therefore, the problem is that one form works as it should (it performs a .php function of sending emails + sends the information to google Sheets), while the other one does not work as it should, IE, only sends the emails. I came to the conclusion that the problem is the tag id="" because I am already without options. I will put down a part of the code so that you understand.

The point is that this 3 information is arranged so for a reason (name, email and phone). I had to go to Google Developers and create an API, then a spreadsheet in Sheets with 3 columns: name, email and phone. Therefore, I understand that the two forms need to have the same communication, for the information to work as it should.

Update: In Stackoverflow English, I asked for help and was told that the variables . val and . css only take the first element, so the question would be to give a way to pull the class, name or something in common in the two forms. However, I don’t have this knowledge of Javascript/Jquery. Looking at the javascript code you can see that what really matters is the end result:

var complete=true & Row += '"'+value+'",';

However, value is defined with a . val: var value = $('#'+field). val();

and the field value is that:

var Fields = ['name','email','telephone'];

There would have to be some way to achieve value through something in common in the two forms. What you tell me?

function submit_form() {    
    // Check Fields
    var complete = true;
    var error_color = '#FFD9D9';
    var fields = ['nome','email','telefone'];
    var row = '';
    var i;
    for(i=0; i < fields.length; ++i) {
        var field = fields[i];
        $('#'+field).css('backgroundColor', 'inherit');
        var value = $('#'+field).val();       
        // Validate Field
        if(!value) {
            if(field != 'message') {
                $('#'+field).css('backgroundColor', error_color);
                var complete = false;
            }
            } else {            
            // Sheet Data
            row += '"'+value+'",';
        }
    }

    // Submission
    if(complete) {      
        // Clean Row
        row = row.slice(0, -1);     
        // Config
        var gs_sid = ''; // Enter your Google Sheet ID here
        var gs_clid = ''; // Enter your API Client ID here
        var gs_clis = ''; // Enter your API Client Secret here
        var gs_rtok = ''; // Enter your OAuth Refresh Token here
        var gs_atok = false;
        var gs_url = '';
        var gs_body = '';        
         // HTTP Request Token Refresh
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {            
            var response = JSON.parse(xhr.responseText);
            var gs_atok = response.access_token;            
            // HTTP Request Append Data
            if(gs_atok) {
                var xxhr = new XMLHttpRequest();
                xxhr.open('POST', gs_url);
                xxhr.setRequestHeader('Content-length', gs_body.length);
                xxhr.setRequestHeader('Content-type', 'application/json');
                xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
                xxhr.onload = function() {
                    if(xxhr.status == 200) {
                        // Success
                        $('#message').html('<p>Row Added to Sheet | <a href="http://snydergroupinc.com/tutorials/tutorial-google-sheets-api.php">Add Another &raquo;</a></p><p>Response:<br/>'+xxhr.responseText+'</p>');
                        } else {
                        // Fail
                        $('#message').html('<p>Row Not Added</p><p>Response:<br/>'+xxhr.responseText+'</p>');
                    }
                };
                xxhr.send(gs_body);
            }            
        };
        xhr.send();
    }
}
<!--MODAL FINAL - FORMULÁRIO CLIQUE OK (MODAL) - ESTE QUE NÃO FUNCIONA POR CONTA DA ID REPETIDA-->
<div  style="color:#000;" id="myModalok" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 style="color:#000;" id="myModalLabel">Preencha o formulário para informações completas do empreendimento Uptown 161</h3>
      </div>
      <div class="modal-body">
        <form id="sheets" name="sheets" class="form-horizontal col-sm-12" method="post" action="c_form/envia.php">
          <div class="form-group"><label>Nome</label><input name="nome" id="nome" value=""class="form-control required" placeholder="Insira seu nome" data-placement="top" data-trigger="manual" data-content="Must be at least 3 characters long, and must only contain letters." type="text"></div>
          <div class="form-group"><label>Mensagem</label><textarea name="mensagem" value="" class="form-control" placeholder="Digite sua mensagem" data-placement="top" data-trigger="manual"></textarea></div>
          <div class="form-group"><label>E-mail</label><input name="email" id="email" class="form-control email" placeholder="Insira seu e-mail" data-placement="top" data-trigger="manual" data-content="Must be a valid e-mail address ([email protected])" type="text"></div>
          <div class="form-group"><label>Telefone</label><input name="telefone" id ="telefone" value="" class="form-control phone" placeholder="Insira seu telefone" data-placement="top" data-trigger="manual" data-content="Must be a valid phone number (999-999-9999)" type="text"></div>
        <input type="hidden" class="form-control" placeholder="Origem" name="Origem" value="<?php echo $_GET["origem"]; ?>">

          <div class="form-group">

          <button type="submit" id="submit" value="Submit" name="submit" class="btn btn-success pull-right" onClick="submit_form()">Enviar</button> <p class="help-block pull-left text-danger hide" id="form-error">&nbsp; Favor corrigir seus dados. </p></div>
        </form>
                            <div id="message" style="display:none;" ></div>
</div>


      </div>
      <div class="modal-footer">
        <!--<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>-->
      </div>
    </div>
  </div>
</div>



<!-- FORMULÁRIO FINAL -->

    <section id="last" class="localiza">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 text-center">
                    <h2 class="margin-top-0 wow fadeIn">Receba mais informações</h2>
                    <hr class="primary">
                    <p>Temos um time de especialistas pronto para tirar suas dúvidas</p>
                </div>
                <div class="col-lg-10 col-lg-offset-1 text-center">
                    <form id="sheets" name="sheets" class="contact-form row" method="post" action="c_form/envia.php">


                        <div class="col-md-4">
                            <label></label>
                            <input id="nome" name="nome" value="" class="form-control" placeholder="Insira seu nome">
                        </div>
                        <div class="col-md-4">
                            <label></label>
                            <input id="email" name="email" 
  • Hi Leo, I posted in stackoverflow in English, I got more answers. The point is that in the javascript I posted, I have the . css and . Val, which only takes the first piece of information. In the case if I have id=name, name=name, it only takes what comes first in the code and is satisfied, which I cannot allow to happen. The point now is that I don’t know how to edit this function to use another method that takes the class, for example.

  • I changed what was requested, but I continue to face the problem.

1 answer

0

A suggestion, modify your ids to be unique.

Now let’s go to the contour solution... modify the following.:

Original:

<button type="submit" ... onclick="submit_form()" />

Proposed:

<button type="submit" ... onclick="submit_form(event)" />

So in your job, do the following.:

Original:

function submit_form() { 
  ...
}

Proposed:

function submit_form(evt) { 
  var scope = $(evt.currenttarget.parentElement);
  ...
}

Finally, when selecting the fields, use the current form as a scope.:

Original:

$('#'+field)

Proposed:

$('#'+field, scope)
  • Hi Tobias, I tried but I still could not. By the help I received in the stack overflow in English, it seems that the functions . val e . css take the first values and are satisfied, so I have two forms, it only takes what comes first in the code and for (I’ve tested this). I don’t know if that’s why, but I realized what you suggested but it hasn’t worked yet.

  • can send me your updated code with the changes I suggested?

  • Good afternoon, You can check now at: onecia.com.br/testeg. Also, follow the link to download the two codes (index.php and javascript): https://www.dropbox.com/sh/17w0rwv017ifwrd/ACV4Fzw-mBmqTGBGAdUgsQa?dl=0 PS: Tested again, does not work yet.

Browser other questions tagged

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