I have the form with action targeted for the specified task. I want to have this form also sent by email. It can be the :mailto option or other.
Mailto on submit button
So When I click the Submit form, the form is submitted. However I would like to attach another action to this action, namely I would like to send this filled form to the email by checking the ckeckbox.
So far I saw, that sending the form by checkbox is possible:
submitting a form when a checkbox is checked
but the pivot thing here is assigning the other form action to my form...
HTML form with multiple "actions"
I tried something like this:
<form id="c_form" action="default_url_when_press_enter" method="get" onsubmit="return validate(this);" target="_blank" >
....
<input type="checkbox" action="mailto:mk#gmail.com" id="cfemail" name="email">
<input class="btn" action="c_form.html" type="submit" id="cfsubmit" value="Submit form">
but it didn't work unfortunately as well as with the code applied below:
document.getElementById("cfsubmit").addEventListener("click", function(){
document.getElementById("c_form").className="submitted";
});
How can I send email along with the form submission when my box is checked?
The full code is available here:
https://jsfiddle.net/ptgbvfen/
So far if I understand your problem correctly, you want to submit the form normally. But if the checkbox is checked you want to perform a mailto function as well.
HTML:
<form id="c_form" onsubmit="return validate(this);" target="_self" >
....
<input type="checkbox" id="openmail" name="email">
<input class="btn" type="button" id="cfsubmit" value="Submit form">
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var mainForm = document.getElementById("c_form"); // Get form element
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = "mailto:mk#gmail.com"; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
mainForm.submit(); // Submits the form
});
Updated___
Removed the action attribute from form element, because you do not need it when you want the form to submit on the current page. Also changed the target attribute to _self so that it will not open new tab whenever you submit the form.
Updated V2_
Made mailto autofill the email content when checkbox checked and form is submitted, as requested. If you find it helpful then kindly upvote, and if you are facing more issue then comment down below. Thanks.
Demo: https://jsfiddle.net/rzos1bwt/
HTML
<form id="c_form" onsubmit="return false;">
<div id="Page1">
<h2 class="property">Property information</h2>
<fieldset>
<figure class="property_information">
<figure class="fig">
<label>
<div class="order">A</div>
<p>Proposed Cable Route<span class="asterisk">*</span></p>
</label>
<br>
<select name="proposed_cable_route" id="cf_proposed_cable_route">
<option value="" disabled selected>-Select your answer-</option>
<option value="External">External</option>
<option value="Internal">Internal</option>
<option value="Combination">PIA</option>
</select>
</figure>
<figure class="fig" id="cf_building_post_2000">
<label>
<div class="order">B</div>
<p>Is the building post 2000?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="building_post_2000" type="radio" value="Yes" selected>Yes
<input name="building_post_2000" type="radio" value="No">No
<br>
</figure>
<figure class="fig" id="cfasbestos">
<label>
<div class="order">C</div>
<p>Do you have asbestos report?
<span class="asterisk">*</span>
</p>
</label>
<br>
<input name="asbestos_report" type="radio" value="Yes" selected>Yes
<input name="asbestos_report" type="radio" value="No">No
<br>
<h3 class="alert">Please contact your team leader for advice!</h3>
</figure>
</figure>
<figure class="fig">
<label>
<div class="order">9</div>
<p>Surveyor<span class="asterisk">*</span></p>
</label>
<br>
<input type="text" name="surveyor" placeholder="Surveyor's name">
<input type="email" name="surveyor_email" placeholder="Email">
<br>
</figure>
<div class="emailreceipt">
<input type="checkbox" id="opemail" name="email">
<label for="opemail">Send me an email receipt of my responses</label>
</div>
<input class="btn" type="submit" id="cfsubmit" value="Submit form">
</fieldset>
</div>
</form>
Javascript
document.getElementById("cfsubmit").addEventListener("click", function() {
var check = document.getElementById("opemail"); // Get checkbox element
var formEl = document.forms.c_form; // Get the form
var formData = new FormData(formEl); // Creates form object
// Get all form data values
var cableRoute = formData.get('proposed_cable_route');
var buildingPost = formData.get('building_post_2000');
var asbestosReport = formData.get('asbestos_report');
var surveyorName = formData.get('surveyor');
var surveyorEmail = formData.get('surveyor_email');
// This will create the subject of form
var subject = "Submission from " + surveyorName;
// This will create body with filled data
var body = 'My name is ' + surveyorName + '\n' + 'My email is ' + surveyorEmail + '\n' + 'Proposed Cable Route: ' + cableRoute + '\n' + 'Is the building post 2000: ' + buildingPost + '\n' + 'Do you have asbestos report: ' + asbestosReport;
// Making the mailto link with urlencoding
var mailTo = "mailto:mk#gmail.com?subject="+encodeURI(subject)+"&body="+encodeURI(body);
if (check.checked == true) { // If checked then fire
let link=document.createElement("a"); // Creates <a> element in DOM
link.href = mailTo; // Adds mailto link to <a>
link.click(); // Clicks the <a> and open default mail app
link.remove();
}
//console.log("mailTo => ", mailTo)
mainForm.submit(); // Submits the form
});
Related
I would like to find out if an image or images could be used to completed form.
If img name = image1, then when clicking on the image/s it should add the image name to a form input field.
The form should have the selected image/s names in the input field.
Eg: if image1 is selected, the value should be image1
This is what I have done so far. I can make it change a para tag but not a form text input...
HTML
<p>Select the images for your music choice</p>
<img src="Images/hiphop.png" onclick="musicTaste('Hiphop')"/>
<form method="POST" action="musictaste.php">
<input type="text" name="musicTasteSelection" id="genre">
Confirm your music taste: <input type="submit" name="submit" id="">
</form>
JS
<script>
function musicTaste(genre) {
document.getElementById('genre').innerHTML = genre;
}
</script>
In your js code, you should be doing this:
document.getElementById('genre').value = genre;
To add multiple images to the input box, do this instead:
document.getElementById('genre').value += genre + ", ";
input elements don't have an .innerHTML property (that property is for non-form field elements that have an opening and closing tag). Form field elements have a .value property.
<p>Select the images for your music choice</p>
<img src="Images/hiphop.png" id="pic" onclick="musicTaste('Hiphop')"/>
<form method="POST" action="musictaste.php">
<input type="text" name="musicTasteSelection" id="genre">
Confirm your music taste: <input type="submit" name="submit" id="">
</form>
JS
<script>
function musicTaste(genre) {
document.getElementById('genre').value = genre;
}
</script>
hoping someone can help me with this.
Firstly to summarize, I have a list of items that each have a 'Book Now' button, once the book now button is clicked then they redirect to their respective pages. What I have added in between this is a modal popup.
So when a new user comes to the site, clicks a book now button on one of the list items, the modal will appear. They then type in some details and submit submit the form
Then, ideally, they would be redirected to the appropriate page. The items with the Book Now button are generated through a loop of Expression Engine entries so the links are never hard coded.
My problem is that the code for the modal form itself cannot be inside the loop of entries and so therefore cannot read which URL to link to once it's submitted so I figured I would have to use JavaScript to solve this.
My thinking was to add a data-link attribute to the Book Now button, then in JavaScript tell the form that once submitted it should redirect to the value inside the data-link attribute of the link that was clicked.
I hope this makes sense to someone. Is this possible? Can someone perhaps offer some advice
Thanks
Edit: added code
<a class="booking-tracker" href="#" data-link="{base_url}ticket/{url_title}">Book now</a>
<div class="modal-wrapper" id="wrapper-modal" style="display:none;">
<form>
Name: <input type="text" name="name" id="name" value="" />
Email: <input type="text" name="email" id="email" value="" />
<input type="hidden" name="redirect" value="redirectvalue here pulled from initial link data-attribute">
<input type="submit" value="submit" />
</form>
</div><!--modal-->
<script>
$(document).ready(function() {
$('.booking-tracker').on("click", function (event) {
if(f24('autoId') == '' && f24('personId') == '') {
document.getElementById('wrapper-modal').style.display='block';
}
else {
window.location = $(this).data('link');
}
});
});
</script>
So this script above will trigger the modal if the user is new to the site and hasn't previously recorded their details, otherwise it will link to the default URL of that link, it's just the form redirect that I'm struggling with
Use data on the button to generate a unique url. When the button is clicked get this data and add it to the hidden element of your form. I did up a little example. Hope it helps!
var redirect_link = 'www.thisisyourredirectlink.com/';
$('.click-for-modal').on('click' , function(e){
e.preventDefault(); // Used anchor tags so prevent default
var redirect_id = $(this).attr('id');
var new_redirect = redirect_link + redirect_id;
$('#redirect').removeAttr('value'); //remove if it has been set previously
$('#redirect').attr('value' , new_redirect); // Add current id
console.log(new_redirect);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="click-for-modal" id="1" href="">Button</a>
<a class="click-for-modal" id="2" href="">Button</a>
<a class="click-for-modal" id="3" href="">Button</a>
<a class="click-for-modal" id="4" href="">Button</a>
<a class="click-for-modal" id="5" href="">Button</a>
<a class="click-for-modal" id="6" href="">Button</a>
<div class="modal-wrapper" id="wrapper-modal" style="">
<form>
Name: <input type="text" name="name" id="name" value="" />
Email: <input type="text" name="email" id="email" value="" />
<input id="redirect" type="hidden" name="redirect" value="redirectvalue here pulled from initial link data-attribute">
<input type="submit" value="submit" />
</form>
</div><!--modal-->
I can't find any answer then ask:
I have to different forms on the page: the one is "ask for call" (placed on every page on the site) and the second is a simple "contact form" (placed only on contact page).
Both are validates without problems, do they are created for also good on the different page. Both has fields which are required. They has different names and IDs.
The error occurs when user on the contact page. There are two forms together. By the order contact is first. And when I use it, a mail sends.
But when I try to send call request with the second form on the page, it doesn't action because on the first form required wasn't filled or didn't match restrictions.
Why submit button from the second form takes data from the first?
Below forms in the order on the contact page and processing functions.
First form (contact)
<form id="message" name="contact_message" onsubmit="return false;" method="post">
<div class="hover">
<label for="message-name">Введите ваше имя:</label>
<input id="message-name" name="name" type="text" placeholder="Имя" title="Пожалуйста, введите ваше имя." required>
</div>
<div class="hover">
<label for="message-email">Введите ваш email адрес:</label>
<input id="message-email" name="email" type="email" placeholder="xxx#xxx.xx" title="Пожалуйста, введите корректно ваш email." required>
</div>
<div class="hover">
<label for="message-text">Введите ваше сообщение:</label>
<textarea id="message-text" name="text" placeholder="Текст сообщения" title="Пожалуйста, введите текст сообщения. Минимум 9 символов." minlength="9" required></textarea>
</div>
<input type="hidden" name="type" value="contact_page">
<button id="submit-contact" class="empty blue button medium" type="submit">Отправить</button>
<div class="c-clearfix"></div>
</form>
The second form
<form id="call-ask-form" name="call-ask-form" class="full-width" onsubmit="return false;" method="post">
<label for="phone-name">Ваше имя</label>
<input id="phone-name" type="text" name="name" placeholder="Введите ваше имя" minlength="2" required>
<label for="phone-phone">Ваш номер телефона (только цифры)</label>
<input id="phone-phone" type="text" name="phone" placeholder="+41234567890" maxlength="16" required>
<label for="phone-time">Время в формате ЧЧ:ММ, с 9 до 17 в будние дни, когда вы ожидаете звонок.</label>
<input id="phone-time" type="text" name="text" placeholder="ЧЧ:ММ" maxlength="5">
<input id="type" name="type" type="hidden" value="call_ask">
<button form="call-ask-form" id="call-submit" class="filled green medium full-width button" type="submit">Отправить запрос</button>
</form>
JS
And here the page_type variable gets data from the first form every time I push submit on the second form. And switch cases on CONTACT, but CALL REQUEST.
$(document).ready(function() {
$("#submit, #call-submit").click(function() {
var proceed = true;
var page_type = $('input[name=type]').val();
//validation
if(proceed)
{
var form;
//choosing type of a message
switch (page_type) {
case 'contact_page' :
// preparing data from CONTACT form
break;
case 'call_ask' :
// preparing data from CALL REQUEST form
break;
case 'calculator' :
break;
default :
}
// ajax post data
$.post('/assets/components/mailer2.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error" style="background-color: red; color: white;">' + response.text + '</div>';
} else {
output = '<div class="success" style="background-color: green; color: white;">' + response.text + '</div>';
}
$(form).append(output).slideDown();
}, 'json');
}
});
Why this happens? Kindly asking you for help.
In the line $('input[name=type]').val();, this will always try to find the value of the first input matching the name criteria on the whole page.
But, note that both of your forms have inputs with the same name.
Javascript will not be very friendly when multiple elements have the same name. Instead, you will either need to rename them or ensure that you better reference which one you are trying to get:
The below code will get you the correct page_type: (Note that in events, this will be set to the current element which in the below case will be one of the <form /> tags which you can use to only traverse it's children using $(this).find(...) as opposed to $(...))
$('form').on('submit', function(e){
var page_type = $(this).find('input[name=type]').val();
alert(page_type);
e.preventDefault();
})
Second image ,First image I have a set of links, which will open a pop-up form.
When the link is clicked,I want to send a parameter to the form and then use it on form submission.
I'm able to set the value to be passed as id of <a> tag. Can I send to further?
<div> <span>Chapter $i:</span>
<a href='$viewlink '>View</a><span class='status'>Status:$status </span>
<a href=$reqlink id=$i data-rel='popup' class='ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left'>Request Access</a></div><br/>";
<form method="post" action=" " id="myPopup" data-role="popup" style="padding:10px">
<h3>Enter your details</h3>
<input type="text" name="name" id="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<input type="date" name="date" id="date" placeholder="Intended completion date" required>
<input type="submit" data-inline="true" value="Submit" name='submit'>
</form>
Is it possible to do in javascript? How to do it?
Option #1:
Set up hidden inputs, and send the values to them when clicking the link. You can then get these on the other end where the form is sent.
(Note: in my code examples I'm explicitly using PHP as that's where you seem to have copied your code snipped from)
echo "<a href='$viewlink' onclick='$(\'#viewlink\').val(1);'>View</a><span class='status'>Status:$status </span>
<!-- Do the following inside the form -->
<input type='hidden' name='viewlink' id='viewlink' value='0' />";
And on the PHP receiving end you can do this:
if ($_POST['viewlink'] == 1) {
// do stuff
}
Option #2:
Alternatively you could send the data to a javascript array, prevent posting on submit of the form, take care of adding the array to the form action as query string, then explicitly send the form.
echo "<a href='$viewlink' onclick='linkClicked('viewlink');'>View</a><span class='status'>Status:$status </span>
This is what you'd do in your javascript file:
var queryString = [];
function linkClicked (type) {
queryString[type] = 1;
}
$("#myPopup").submit(function(event) {
event.preventDefault();
$(this).attr('action', $(location).attr('host') + $.param(queryString));
$(this).submit();
});
And on the PHP receiving end you can do the following (note the $_POST from above has changed to $_GET):
if ($_GET['viewlink'] == 1) {
// do stuff
}
try this..
<a id = 'yourid' class = 'mybtn'>click me..</a>
<form id = 'myform'>
....
</form>
Jquery
$(document).ready(function(){
$('.mybtn').click(function(){
var id = $(this).attr('id');
var SubmitForm = $("#myform").serializeArray();
$.post("somepage.php",
{
SubmitForm:SubmitForm,
ID:id
},
function(res){
alert(res);//your result..
});
});
I am a newbie to javascript, I am making a simple script which will show appended link with the data entered in input field, Basically it should get the data from input field and generate link with data being submitted in input field.
Similar to the example below
Input: tony#mail.com ...> after clicking Send button
processing....
Output link: www.domain.com/route.php?email=tony#mail.com
I found this code similar to mine but it wont works like i am looking for.
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<a href="#"
onclick="this.href = ('http://' + document.getElementById('foosite').value + 'www.domain.com/route.php?email=')"
target="_blank">send</a>
Is that possible in javascript to make a script like this which will generate output without reloading the page?
You have the getelement in the wrong place. It should be like this if you want to do it that way.
<input type="text" name="foo" id="foosite1" value="" />
send
<input type="text" name="foo" id="foosite2" value="" />
send
http://jsfiddle.net/bowenac/J2Mc5/3/
Split your JS logic from your HTML
HTML
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
</p>
send
<div id="url_value"></div>
JS
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var route = "http://www.domain.com/route.php?email=" + value + ', ';
var data = "http://www.domain.com/data.php?email=" + value + ', ';
var form = "http://www.domain.com/form.php?email=" + value;
document.getElementById('url_value').innerHTML = route + data + form
}
DEMO
You can add form to your html code and send data to server using form submit, in this case you can change the action of the form before submit to custom link.
<form name="form1" action="" onSubmit="onsubmit(this)">
<p>
Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
<input type="submit" value="send" />
</p>
</form>
<script>
function onsubmit(form)
{
//change the action of the form to your link.
form.submit();
}
</script>