How to use two forms with the same ID?

1

Hello,

I found a problem. I'm doing an HTML form integration with Google Sheets. The issue is that I have two forms, I'm not excellent in Javascript but it seems that the "var fields" function only works with the HTML id. So, the problem is that a form works as it should (it performs a .php function of sending emails + sends the information to google sheets), while the other does not work as it should, that is, it only sends the emails. I came to the conclusion that the problem is the id="" tag because I'm already without options. I'll put down a part of the code for you to understand.

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

Update: In StackOverflow English, I asked for help and was told that the .val and .css variables take only the first element, so the question would be to give a form of pulling by class, name or something in common on both forms. However, I do not have this knowledge of Javascript / Jquery. Looking at the javascript code you may realize that what really matters is the end result:

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

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

and the field value is this:

var fields = ['name', 'email', 'phone'];

You'd have to have some way of achieving value through something in common on both forms. What do you guys 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" 
    
asked by anonymous 18.09.2017 / 16:14

1 answer

0

A suggestion, modify your ids to be unique.

Now let's go to the contouring solution ... modify the following.:

Original:

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

Proposed:

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

Then in your role, 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 scope.:

Original:

$('#'+field)

Proposed:

$('#'+field, scope)
    
20.09.2017 / 14:48