1 button 2 functions

I've got a conflict issue with a form. The idea is that I need to store the datas in the form field in a table with a local storage in Javascript, and I need to send an email simultaneously with the same button with PHP. When I try it, either the button implement the table, either it send the mail. It depends of the position of the action inside the arrows. Here is my code :

<script>
    var Contacts = {
      index: window.localStorage.getItem("Contacts:index"),
      $table: document.getElementById("contacts-table"),
      $form: document.getElementById("contacts-form"),
      $button_save: document.getElementById("contacts-op-save"),
      $button_discard: document.getElementById("contacts-op-discard"),

      init: function() {
        // initialize storage index
        if (!Contacts.index) {
          window.localStorage.setItem("Contacts:index", Contacts.index = 1);
        }

        // initialize form
        Contacts.$form.reset();
        Contacts.$button_discard.addEventListener("click", function(event) {
          Contacts.$form.reset();
          Contacts.$form.id_entry.value = 0;
        }, true);
        Contacts.$form.addEventListener("submit", function(event) {
          var entry = {
            id: parseInt(this.id_entry.value),
            first_name: this.first_name.value,
            last_name: this.last_name.value,
            company: this.company.value,
            address: this.address.value,
            city: this.city.value,
            zip: this.zip.value,
            state: this.state.value,
            country: this.country.value,
            phone: this.phone.value,
            email: this.email.value,
            nature_of_contact: this.nature_of_contact.value,
          };
          if (entry.id == 0) { // add
            Contacts.storeAdd(entry);
            Contacts.tableAdd(entry);
          }
          else { // edit
            Contacts.storeEdit(entry);
            Contacts.tableEdit(entry);
          }

          this.reset();
          this.id_entry.value = 0;
          event.preventDefault();
        }, true);

        // initialize table
        if (window.localStorage.length - 1) {
          var contacts_list = [], i, key;
          for (i = 0; i < window.localStorage.length; i++) {
            key = window.localStorage.key(i);
            if (/Contacts:\d+/.test(key)) {
              contacts_list.push(JSON.parse(window.localStorage.getItem(key)));
            }
          }

          if (contacts_list.length) {
            contacts_list
              .sort(function(a, b) {
                return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
              })
              .forEach(Contacts.tableAdd);
          }
        }
        Contacts.$table.addEventListener("click", function(event) {
          var op = event.target.getAttribute("data-op");
          if (/edit|remove/.test(op)) {
            var entry = JSON.parse(window.localStorage.getItem("Contacts:"+ event.target.getAttribute("data-id")));
            if (op == "edit") {
              Contacts.$form.first_name.value = entry.first_name;
              Contacts.$form.last_name.value = entry.last_name;
              Contacts.$form.company.value = entry.company;
              Contacts.$form.address.value = entry.address;
              Contacts.$form.city.value = entry.city;
              Contacts.$form.zip.value = entry.zip;
              Contacts.$form.state.value = entry.state;
              Contacts.$form.country.value = entry.country;
              Contacts.$form.phone.value = entry.phone;
              Contacts.$form.email.value = entry.email;
              Contacts.$form.nature_of_contact.value = entry.nature_of_contact;
              Contacts.$form.id_entry.value = entry.id;
            }
            else if (op == "remove") {
              if (confirm('Are you sure you want to remove "'+ entry.first_name +' '+ entry.last_name +'" from your contacts?')) {
                Contacts.storeRemove(entry);
                Contacts.tableRemove(entry);
              }
            }
            event.preventDefault();
          }
        }, true);
      },

      storeAdd: function(entry) {
        entry.id = Contacts.index;
        window.localStorage.setItem("Contacts:index", ++Contacts.index);
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
      },
      storeEdit: function(entry) {
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
      },
      storeRemove: function(entry) {
        window.localStorage.removeItem("Contacts:"+ entry.id);
      },

      tableAdd: function(entry) {
        var $tr = document.createElement("tr"), $td, key;
        for (key in entry) {
          if (entry.hasOwnProperty(key)) {
            $td = document.createElement("td");
            $td.appendChild(document.createTextNode(entry[key]));
            $tr.appendChild($td);
          }
        }
        $td = document.createElement("td");
        $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>';
        $tr.appendChild($td);
        $tr.setAttribute("id", "entry-"+ entry.id);
        Contacts.$table.appendChild($tr);
      },
      tableEdit: function(entry) {
        var $tr = document.getElementById("entry-"+ entry.id), $td, key;
        $tr.innerHTML = "";
        for (key in entry) {
          if (entry.hasOwnProperty(key)) {
            $td = document.createElement("td");
            $td.appendChild(document.createTextNode(entry[key]));
            $tr.appendChild($td);
          }
        }
        $td = document.createElement("td");
        $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>';
        $tr.appendChild($td);
      },
      tableRemove: function(entry) {
        Contacts.$table.removeChild(document.getElementById("entry-"+ entry.id));
      }
    };
    Contacts.init();
  </script>
<form action="mailer.php" method="post" class="onerow">
           
      <label class="col6">First name:
      <input type="text" name="first_name" />
      </label>
   
      <label class="col6">Last name:
      <input type="text" name="last_name" />
      </label>

      <label class="col6">Company:
     <input type="text" name="company" />
     </label>
    
      <label class="col6">Address:
      <input type="text" name="address" />
      </label>

      <label class="col6">City:
      <input type="text" name="city" />
      </label>

      <label class="col6">Postal/zip code:
      <input type="text" name="zip" />
      </label>

      <label class="col6">State/province:
      <input type="text" name="state" />
      </label>

      <label class="col6">Country:
      <input type="text" name="country" />
      </label>

      <label class="col6">Phone number:
     <input type="text" name="phone" />
      </label>

      <label class="col6">Email:
      <input type="text" name="email" />
      </label>

      <label class="col12">Why are you looking for our solutions ?
      
        <SELECT name="nature_of_contact" size="1">
          <OPTION>I'm a distributor and I want to sell your products in my country.
          <OPTION>I'm a beautician I want to buy a product.
          <OPTION>I'm a doctor.
          <OPTION>I'm a distributor.
        </SELECT>
      </label>
    
    <div class="col12">
      <input type="button" id="contacts-op-discard" value="Discard" />
       <input type="submit" id="contacts-op-save" value="Save" />
    <input type="hidden" name="id_entry" value="0" />
    </div>
  </form>
  </div>
  <div></div>
  <div id="tablecontrol" class="col12">
  <h1>Contacts</h1>
  <table id="contacts-table">
    <tr id="contacts-head">
      <th>ID</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Company</th>
      <th>Address</th>
      <th>City</th>
      <th>Postal/Zip</th>
      <th>State/province</th>
      <th>Country</th>
      <th>Phone number</th>
      <th>Email</th>
      <th>Kind of prospect</th>
      <th>Actions</th>
    </tr>
  </table>
  </div>
  </div>

See JSFIDDLE

Upvotes: 3

Views: 198

Answers (2)

Reporter
Reporter

Reputation: 3948

One way would be:

  1. Change the submit button from type 'submit' to 'button' and add the event onClick()to it.
  2. Create a function -let's say readFromdata()- that reads the values from your form. Store the data into a container.
  3. Create a function -let's say sendFromdata()- that sends the data to your php script. Hint: Ajax would be your friend. Configure your Ajax so, that the data will be send asyncrosly.
  4. Create a function -let's say printFOverview()- that extends your html table, for the displaying the result.
  5. Call sendFromdata() and printFOverview() within the function readFromdata() and pass the data container to these methods.
  6. Add the call readFromdata() to the attribute onClick().

Upvotes: 1

Daniel Gasser
Daniel Gasser

Reputation: 5133

You could do the following:

  1. Add an event.preventDefault() to your handler
  2. Then store things in localStorage
  3. If things are stored submit the form with Contacts.$form.submit();

EDIT

Change the event handler from submit to click and remove it from the form to add it to the Contacts.$button_save button and add a preventDefault() just after.

As you changed the event handler from the form to the button you need to change the form values from this to Contacts.$form because this was in the scope of the form which is not the case anymore.

Contacts.$button_save.addEventListener("click", function(event) {
    event.preventDefault();
    var entry = {
        id: parseInt(Contacts.$form.id_entry.value),
        first_name: Contacts.$form.first_name.value,
        last_name: Contacts.$form.last_name.value,
   // and so on

Remove the input type="submit" and create a normal button instead:

<button id="contacts-op-save">Save</button>

Then you could submit the form after storing in storeAdd / storeEdit functions as said with Contacts.$form.submit();.

      storeAdd: function(entry) {
        entry.id = Contacts.index;
        window.localStorage.setItem("Contacts:index", ++Contacts.index);
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
        Contacts.$form.submit();
      },
      storeEdit: function(entry) {
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
        Contacts.$form.submit();
      },
      storeRemove: function(entry) {
        window.localStorage.removeItem("Contacts:"+ entry.id);
        // eventually here too?
        Contacts.$form.submit();

      },

Also you call the form element by its id , but the form has no id assigned.

$form: document.getElementById("contacts-form")

So give your form that ID:

<form id="contacts-form" action="mailer.php" method="post" class="onerow">

Upvotes: 0

Related Questions