Simple send form for whatsapp - javascript

I'm creating a simple form to send messages to a specific WhatsApp contact. I was trying to use a javascript, but I'm not getting it, the link is not going the way I want.
I'm using the following code:
$(function() {
$('#send-message-whatsapp').on('click', 'button', function(e) {
e.preventDefault();
const $form = $("#send-message-whatsapp");
const phone = '559999999999';
const nome = $form.children('input[name="nome"]').val();
const email = $form.children('input[name="email"]').val();
const wpp = $form.children('input[name="wpp"]').val();
const cep = $form.children('input[name="cep"]').val();
const rua = $form.children('input[name="rua"]').val();
const bairro = $form.children('input[name="bairro"]').val();
const complemento = $form.children('input[name="complemento"]').val();
const action = "https://wa.me/" + phone + "?text=" + nome + email + wpp + cep + rua + bairro + complemento;
$form.attr('action', action);
$form.attr('target', '_blank');
$form.submit();
});
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<form id="send-message-whatsapp">
<div class="form-label-group">
<input type="text" name="nome" class="form-control" placeholder="Seu nome" required="" autofocus="">
<label for="nome">Nome completo</label>
</div>
<div class="form-label-group">
<input type="email" name="email" class="form-control" placeholder="Seu e-mail" required="" autofocus="">
<label for="inputEmail">Seu E-mail</label>
</div>
<div class="form-label-group">
<input type="text"name="wpp" class="form-control" placeholder="Seu e-mail" required="" autofocus="">
<label for="wpp">Seu Número/WhatsApp</label>
</div>
<div class="form-label-group">
<input type="text" id="cep" name="cep" class="form-control" placeholder="Seu cep" required="" autofocus="">
<label for="cep">Seu CEP</label>
</div>
<div class="form-label-group">
<input type="text" id="rua" name="rua" class="form-control" placeholder="Sua Rua" required="" autofocus="">
<label for="rua">Nome da sua Rua</label>
</div>
<div class="form-label-group">
<input type="text" id="bairro" name="bairro" class="form-control" placeholder="Seu Bairro" required="" autofocus="">
<label for="rua">Bairro</label>
</div>
<div class="form-label-group">
<input type="text" name="complemento" class="form-control" placeholder="Complemento" required="" autofocus="">
<label for="rua">Complemento</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
When I click on send the link does not go with the filled texts ..
This form will be used to capture leads in an internal campaign for my company.
Also if you have any solution in PHP I would like to know if you can help me ...
Sorry my english, i'm using translator...

From MDN:
Multiple query parameters are separated by & instead of the initial ?.
The first URL parameter is denoted by a ? at the end of the URL path. After that, additional parameters are given using &.
For example: https://www.example.com?param1=a&param2=b
As Deepak Kamat said, you may also wish to look into encoding your URL parameters.

Just use serializeArray to get an array of the fields (convert it to object), then make an array for the text and then join() it with your separator, plus dont forget encodeURIComponent else user could inject own params.
$(function() {
$('#send-message-whatsapp').on('click', 'button', function(e) {
e.preventDefault();
const $form = $("#send-message-whatsapp");
const phone = '559999999999';
// get object i.e {key: 'value'} of form
let data = {}
$form.serializeArray().forEach(v => data[v.name] = v.value)
// make the ?text= payload,
// - could use .filter() here too if you dont want empty values
const text = [
data.nome,
data.email,
data.wpp,
data.cep,
data.rua,
data.bairro,
data.complemento
].join(' - ') // change to what you want sep to be
// make the url
const action = "https://wa.me/" + phone + "?text=" + encodeURIComponent(text);
console.log(action)
/*
$form.attr('action', action);
$form.attr('target', '_blank');
$form.submit();
*/
});
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<form id="send-message-whatsapp">
<div class="form-label-group">
<input type="text" name="nome" class="form-control" placeholder="Seu nome" required="" autofocus="">
<label for="nome">Nome completo</label>
</div>
<div class="form-label-group">
<input type="email" name="email" class="form-control" placeholder="Seu e-mail" required="" autofocus="">
<label for="inputEmail">Seu E-mail</label>
</div>
<div class="form-label-group">
<input type="text" name="wpp" class="form-control" placeholder="Seu e-mail" required="" autofocus="">
<label for="wpp">Seu Número/WhatsApp</label>
</div>
<div class="form-label-group">
<input type="text" id="cep" name="cep" class="form-control" placeholder="Seu cep" required="" autofocus="">
<label for="cep">Seu CEP</label>
</div>
<div class="form-label-group">
<input type="text" id="rua" name="rua" class="form-control" placeholder="Sua Rua" required="" autofocus="">
<label for="rua">Nome da sua Rua</label>
</div>
<div class="form-label-group">
<input type="text" id="bairro" name="bairro" class="form-control" placeholder="Seu Bairro" required="" autofocus="">
<label for="rua">Bairro</label>
</div>
<div class="form-label-group">
<input type="text" name="complemento" class="form-control" placeholder="Complemento" required="" autofocus="">
<label for="rua">Complemento</label>
</div>
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
As data is key value you could also do the following to create a nicer message:
$(function() {
$('#send-message-whatsapp').on('click', 'button', function(e) {
...
// uppercase first letter of Key: value i.e:
/*
[
"Nome: ",
"Email: ",
"Wpp: ",
"Cep: ",
"Rua: ",
"Bairro: ",
"Complemento: "
]
*/
let text = []
$form.serializeArray().forEach(v => text.push(v.name.charAt(0).toUpperCase() + v.name.slice(1) + ': ' + v.value))
// make the url, join text with a new line
const action = "https://wa.me/" + phone + "?text=" + encodeURIComponent(text.join('\n'));
...
});
});
Then your message will look like:
Nome: Loz C
Email: internet-way#example.com
Wpp: Don't know what this is
Cep: Don't know what this is
Rua: Don't know what this is
Bairro: Full of chavs
Complemento: It's ayyok

Related

How to transfer data from a form for Whatsapp to another page before submitting

I created a form in HTML that sends the data to WhstsApp, but I need that before going directly to WhatsApp, go through another page so that I can put the Google Ads conversion code.
Here's a print of the configuration:
https://prnt.sc/qlG3cVC_CzjG
Code:
<div class="row register-form">
<div class="col-md-12">
<form autocomplete="off">
<div class="form-group">
<input
type="text"
name="Name"
id="name"
class="form-control"
placeholder="Seu Nome *"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<input
type="text"
name="Email"
id="email"
class="form-control"
placeholder="Seu E-mail *"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<input
type="number"
name="Phone"
id="phone"
class="form-control"
placeholder="Seu Telefone*"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<select class="form-control" id="service">
<option>Motivo do Contato</option>
<option>Quero um Orçamento</option>
<option>Outros Assuntos</option>
</select>
</div>
<div class="form-group">
<input
type="submit"
onclick='gotowhatsapp()'
name="submit"
id="submit"
class="btnSubmit btn-block"
value="ENVIAR"
/>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
function gotowhatsapp() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var service = document.getElementById("service").value;
var url = "https://wa.me/5511981252689?text="
+ "*Nome*: " + name + "%0a"
+ "*Telefone*: " + phone + "%0a"
+ "*E-mail*: " + email + "%0a"
+ "*Motivo*: " + service;
window.open(url, '_blank').focus();
}
How can I make this data go to another page and then redirect to WhatsApp?
change this your script js, example :
<script>
function gotowhatsapp() {
var name = document.getElementById("name").value;
var nohp = document.getElementById("nohp").value;
var pesan = document.getElementById("pesan").value;
var url = "https://api.whatsapp.com/send?phone="+ nohp +"&text="
+ "Nama: " + name + "%0a"
+ "Nohp: " + nohp + "%0a"
+ "Isi Pesan: " + pesan;
window.open(url, '_blank').focus();
}
</script>
hope can help you

How to valid checkbox in a form

I have a basic question but i can't find the solution .
how can i force my user to check the box : accept the condition ? (j'acceptes les conditions d'utilisations = i agree terms & conditions )
here is a pictures of my form :
here is my HTML:
<section id="formDom">
<form class="column g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Nom</label>
<input type="text" class="form-control" placeholder="Dupont" id="firstName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">prénom</label>
<input type="text" class="form-control" placeholder="Jean" id="lastName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Adresse mail</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="email" class="form-control" id="email" aria-describedby="inputGroupPrepend"
placeholder="jeandupont#gmail.com" required>
<div class="invalid-feedback">
Adresse mail requise
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Ville</label>
<input type="text" class="form-control" placeholder="Paris" id="city" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom03" class="form-label">Adresse</label>
<input type="text" class="form-control" placeholder="1 rue de Paris" id="adress" required>
<div class="invalid-feedback">
adresse réquise
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
J'accepte les conditions d'utilisations
</label>
<div class="invalid-feedback">
Vous devez accepteer les conditions d'utilisations
</div>
</div>
</div>
<div class="col-md-4">
<button id="buyBtn" class="btn btn-primary basket-btn" type="submit">Acheter</button>
</div>
</form>
</section>
Actually the user is forced to fill the form but he can submit without check the box ( accept condition )
Here is the JS :
function validForm() {
const form = document.querySelector('.needs-validation');
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
cameraIds = getBasket().map(item => { return item.id });
const contact = {
email: document.getElementById("email").value,
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
city: document.getElementById("city").value,
address: document.getElementById("adress").value,
}
createOrder(contact, cameraIds, (order, error) => {
if (error) {
alert('Merci de remplir le formulaire');
} else {
localStorage.clear();
location.assign(`confirmation.html?id=${order.orderId}`)
}
form.classList.add('was-validated');
})
})
}
validForm();
PS : i'm using BOOTSTRAP but i think you got it ^^
if(document.getElementById('invalidCheck').checked==true)
//you'r accepted the terms
else
//you should accept the terms
You can check if a checkbox is checked or not by testing the checked property of the input element:
var isChecked = document.querySelector('input[type="checkbox"]').checked;
if(!isChecked) {
alert("You must accept the terms before proceeding");
}
In your case, it will be:
var isChecked = document.querySelector('.needs-validation .form-check-input').checked;
You can check for document.getElementById("").checked

Is there a vanilla JavaScript way to change the value of an input field

What I am trying to achieve is for the value of the id="origin" input field to be updated as you type in the id="pickup" field.
const pickup = document.querySelector('#pickup')
const dropoff = document.querySelector('#dropoff')
const origin = document.querySelector('#origin')
const destination = document.querySelector('#destination')
const submit = document.querySelector('#submitForm')
pickup.addEventListener('input', (e) => {
origin.value = e.target.value
})
.hidden {
opacity: 0;
}
<form>
<div class="form-group">
<label for="pickup">Pickup</label>
<input type="text" class="form-control" id="pickup" aria-describedby="pickupHelp">
<input type="text" class="form-control hidden" id="origin" value="empty">
<small id="pickupHelp" class="form-text text-muted">Enter your pickup location</small>
</div>
<div class="form-group">
<label for="pickup">Drop-off</label>
<input type="text" class="form-control" id="dropoff" aria-describedby="dropoffHelp">
<input type="text" class="form-control hidden" id="destination" value="">
<small id="dropoffHelp" class="form-text text-muted">Enter your drop-off location</small>
</div>
<button type="submit" class="btn btn-primary" id="submitForm">Submit</button>
</form>
I found the solution I was looking for. Sorry for not clearly stating what I wanted to do.
pickup.addEventListener('input', (e) => {
//changed to .defaultValue instead of just .value
origin.defaultValue = e.target.value
})

How to hide/show a text-box base on other text-box in Laravel 4?

Goal
show email confirm when a user start editing the email section.
hide the email confirm text-box if the user doesn't touch it.
Don't do anything if the user only edit the username part.
Edit Form
username* __________________________
email* __________________________
email confirm* _____________________
HTML/BLADE
<div class="form-group">
<label class="col-sm-3 control-label required ">Username </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('username', isset($user->username) ? $user->username : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label required ">Email </label>
<div class="col-sm-9 form-group float-label-control ">
{{ Form::text('email', isset($user->email ) ? $user->email : '' , array('id'=>'form-field-icon-2')); }}
</div>
</div>
HTML
<label> Username </label><br>
<input type="text" name="username"><br>
<label> Email </label><br>
<input type="text" name="email" id="email"><br>
<label id="l-email-conf" > Email Confirm </label><br>
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
JS
$('#l-email-conf').hide();
$('#email-conf').hide();
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
$('#email-conf').show();
$('#l-email-conf').show();
}
});
JSFiddle
Inline javascript could be an elegant solution if you don't want to write a function.
onkeyup and onkeydown events will do the job and you don't need jQuery
<form>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" onkeyup="this.parentNode.nextElementSibling.style.display = 'block';" onkeydown="this.parentNode.nextElementSibling.style.display = 'none';"/>
</p>
<p id="confirm-email">
<label for="confirm">Confirm email</label>
<input type="text" name="confirm" id="confirm"/>
</p>
</form>
CSS:
#confirm-email {
display: none;
}
Example: jsFiddle
Say this is your HTML -
<input type="text" name="username">
<input type="text" name="email" id="email">
<input type="text" name="email_confirm" disabled="disabled" id="email-conf">
<script>
// Use jQuery event handlers
$('#email').on('input', function (event) {
var text = $(this).val();
if (text === '') { // If email is empty
$('#email-conf').prop('disabled', true);
} else {
$('#email-conf').prop('disabled', false);
}
});
</script>
jsFiddle
P.S. - U can toggle hide/show instead of disabling also.

jQuery's val() returns empty string on bootstrap popover input field

I have a bootstrap popup form with a few input fields. I've added a submit button to the form, that triggers client-side JS validation. However, when the button is clicked, the current value of the input fields is not captured by jQuery's val() method: I just get an empty string.
Here is the markup:
<div class="popover fade right in" style="top: -154.5px; left: 249px; display: block;">
<div class="arrow">
</div>
<h3 class="popover-title">New Job Site contact</h3>
<div class="popover-content">
<form class="popover-form form-horizontal" id="newjobsite_contact_form" accept-charset="utf-8" method="post" action="http://dev.temperature/home/#">
<div class="form-group">
<div class=" required ">
<input type="text" class="form-control" id="popover-first_name" required="1" placeholder="First name" value="" name="first_name">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Phone" value="" name="phone">
</div>
<div class="">
<input type="text" class="form-control" placeholder="Mobile" value="" name="mobile">
</div>
<div class="">
<input type="email" class="form-control" placeholder="Email" value="" name="email">
</div>
<div class="">
<input type="url" class="form-control" placeholder="Website" value="" name="website">
</div>
</div>
<div class="popover_buttons">
<button class="btn btn-success" onclick="submit_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_submit">Submit</button>
<button class="btn btn-warning" onclick="close_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_cancel">Cancel</button>
</div>
</form>
</div>
</div>
Here is the JS:
function submit_newjobsite_contact() {
errors_found = validate_popover_form($('#newjobsite_contact_form'));
if (errors_found.length == 0) {
// Form values submitted to PHP code through AJAX request here
} else {
error_msg = "Please check the following errors:\n";
$(errors_found).each(function(key, item) {
error_msg += "- "+item.message+"\n";
});
alert(error_msg);
}
}
function validate_popover_form(form_element) {
found_errors = [];
$('span.error').remove();
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
console.log($(item).val()); // More validation here, just putting debugging code instead
});
return found_errors;
}
What am I doing wrong? All other attributes for these input fields are being correctly retrieved by jQuery, just not the value after I've typed text into them.
The answer to this problem couldn't be found here because I didn't post the whole source JS, which is too large. What really happened is that I accidentally cloned the popover form, which led to a duplication of the input fields.
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
I Modified it to:
form_element.find('select,input').each(function(key, item) {
if ($(this).data('required') == '1' && $(this).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(this).attr('name'), message: "A value for "+$(this).attr('placeholder')+" is required"});
}
Try using data attributes so instead of using required="1" use data-required="1"
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
so your input should be like this:
<input type="text" class="form-control" data-required="1" placeholder="Surname" value="" name="surname">

Categories