An old thread on Stack Overflow discusses how to use JavaScript to fill in a mailto email:
Sending emails with Javascript
I was interested in applying the technique, but couldn't get it to work.
In the code below, when I set a breakpoint on return false in the makecontact() method, and look at the URL that it logs, it looks fine.
But the browser does not open the email client.
If I hardcode the same URL in an href in the Submit button, then it launches the email client.
Why doesn't setting the href work?
ANSWER: It was the wrong href.
Fixed version:
<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">
<!--
var submit = document.getElementById("submit");
function getreason() {
var radios, i, radio;
radios = document.getElementsByName("reason");
for (i = 0; i < radios.length; i += 1) {
radio = radios[i];
if (radio.checked) {
break;
}
}
return encodeURIComponent(radio.value);
}
function makecontact(e) {
var subject, name, text;
subject = getreason();
name = document.getElementById("name").value;
text = document.getElementById("contacttext").value;
body = "From: '" + name + "', Content: '" + text + "'";
body = encodeURIComponent(body);
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
console.log(document.location.href);
e.preventDefault();
return false;
}
if (submit.addEventListener) {
submit.addEventListener("click", makecontact, true);
} else if (form.attachEvent) {
submit.attachEvent("onclick", makecontact);
} else {
submit.click = makecontact;
}
//-->
</script>
</div>
body = "From: '
" + name + "
', Content: '
" + text + "
'";
This is not valid JavaScript. It will cause an "Unterminated string constant" error. Try this instead:
body = "From: '\n" + name + "\n', Content: '\n" + text + "\n'";
You have two main problems:
button elements don’t have hrefs (HTML4, HTML5). Setting one won’t do anything. At the end of your submit handler, you should instead set document.location.href:
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
You can’t have literal newlines in strings in JavaScript. Use \n instead:
body = "From: ' \n" + name + " \n', Content: ' \n" + text + " \n'";
Also be aware…
You should accept an event object in your event handler, and call event.preventDefault() instead of just returning false from your event handler, to stop the form from being submitted.
There’s no function called resume, but you’re using it if neither addEventListener nor attachEvent exists.
Related
how to remove the emails while unchecking the checkbox from text area, there are multiple emails generated dynamically i can remove all the emails while unchecking the checkbox except the first one...
here is my code
contactsCheckbox is id of checkboxes
showList is id of teenter code herextarea
var email = "";
$(document).on('change', "#contactsCheckbox", function () {
email = "";
if (this.checked) {
email = $(this).val().trim() + ";";
$("#showList").val($("#showList").val() + email);
}
else {
email = this.value;
var strValAdded = $("#showList").val().toString();
var rrr = strValAdded.indexOf(email.trim() + ";");
if (strValAdded.indexOf(email.trim() + ";"))
strValAdded = strValAdded.replace(email.trim() + ";", "");
if (strValAdded.indexOf(email.trim()))
strValAdded = strValAdded.replace(email.trim(), "");
$("#showList").val(strValAdded);
}
});
stringbuilder.Append("<div class=\"checkbox\">");
stringbuilder.Append("<label><input type =\"checkbox\" id=\"contactsCheckbox\" class=\"chk\" value=\"" + data.Email + "\">" + data.Email + "</label>");
stringbuilder.Append("</div>");
So first, element IDs are supposed to be unique. It is not your issue but it is very bad practice and you should correct that anyway. It will cause you more headaches down the road if you do not learn that now.
Your real issue is that your "if" statements are triggering false when you get to a value with a zero index. It is interpreting the zero index as a boolean value check:
Change:
if (strValAdded.indexOf(email.trim() + ";"))
to
if (strValAdded.indexOf(email.trim() + ";") > -1)
Example attached and I put an alert cmd in there so you can more visibly see what is happening with the 0 index boolean check. I also changed your change trigger to look by class instead of ID because your are going to fix your html to no longer be invalid in the near future...hopefully.
$(document).on('change', ".chk", function () {
if (this.checked) {
email = $(this).val().trim() + ";";
$("#showList").val($("#showList").val() + email);
}
else {
email = this.value;
var strValAdded = $("#showList").val().toString();
var rrr = strValAdded.indexOf(email.trim() + ";");
alert(Boolean(strValAdded.indexOf(email.trim() + ";")));
if (strValAdded.indexOf(email.trim() + ";") > -1) {
strValAdded = strValAdded.replace(email.trim() + ";", "");
}
if (strValAdded.indexOf(email.trim()) > -1){
strValAdded = strValAdded.replace(email.trim(), "");
}
$("#showList").val(strValAdded);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever1#wherwever.com"> whatever1#wherwever.com</label>
</div>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever2#wherwever.com"> whatever2#wherwever.com</label>
</div>
<div class="checkbox">
<label><input type ="checkbox" id="contactsCheckbox" class="chk" value="whatever3#wherwever.com"> whatever3#wherwever.com</label>
</div>
<input type="text" name="lname" style="width: 100%" id="showList" disabled >
I'm working on a form using Parsley form validation and am running into one last issue before it's all good to go. This is my first time using Parsley too.
I have this bit of custom script to autofill hyphens and parentheses:
<script type="text/javascript">
$("#inf_field_Phone1").on("change keyup paste", function () {
var output;
var input = $("#inf_field_Phone1").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#inf_field_Phone1").val(output);
});
</script>
When tabbing through the form fields though to double check that all works well and I get to the phone number field, the first parenthesis autofills, and then when I submit the form, Parsley accepts that as a valid phone number. Here is the HTML:
<form accept-charset="UTF-8" id='become-partner-form' method="POST" name='Form'>
<div class="col-md-6">
<input type="tel" class="form-control tc-custom-focus" id="inf_field_Phone1" name="inf_field_Phone1" placeholder="Phone*" data-parsley-trigger='change' data-parsley-required>
</div>
And this may be unrelated but just in case, here is the js that is binding Parsley to the form:
<script type="text/javascript">
$(function () {
$('#become-partner-form').parsley().on('field:validated', function() {
var ok = $('.parsley-error').length === 0;
$('.bs-callout-warning').toggleClass('invisible', ok);
})
});
</script>
Please let me know if you need a jsfiddle or anything to help out (I don't post here much!)
Any ideas on how to prevent the form submit without a full valid phone number?
First, you probably want to use the input event instead of change (useless in your case btw), keyup and paste.
Parsley uses the inputevent, so as long as your code runs before parsley's (i.e. if you bind your autofill code before Parsley), you should be ok.
I'm trying to create a sort of posting system and it works for the most part, but when the post button is clicked, the input field doesn't get reset. I tried a bunch of different ways and none of them have worked, so here is the last one I tried (CodePen sets up the skeleton code so it wouldn't be the problem) :
HTML:
<form id="post" name="write">
<div class="textbox">
<input class="postwriter" name="post" type="text" placeholder="What's on your mind?" id="myPost">
<button id="Post" onclick= "return write_below(this); return formReset();" value="submit" >Post</button>
</div>
</form>
<div class="posts" id="postDisplay">
<p class="para"><span id='display'></span></p>
</div>
JavaScript:
function write_below(form) {
var input = document.forms.write.post.value;
document.getElementById('display').innerHTML += "<p>" + Math.floor(Math.random()*20) + ": " + input + "</p>" + "<br/>";
return false;
}
function formReset(){
document.getElementById("post").reset();
}
Your onclick looks like this:
onclick="return write_below(this); return formReset();"
Which translates to:
return write_below(this);
return formReset();
After the first return, the script ends. So remove the first return. Your code should look like:
onclick="write_below(this); formReset(); return false;"
Having said that, the return false here, makes no sense, so get rid of it.
function write_below(form) {
var input = document.forms.write.post.value;
document.getElementById('display').innerHTML += "<p>" + Math.floor(Math.random()*20) + ": " + input + "</p>" + "<br/>";
}
Note: All your IDs look similar, which might make the developers or someone who sees your code mad. Is that your intention? 😂
I'm passing through some issues while trying to make this code work.
The JavaScript part :
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
function post() {
if (name === "") {
alert("You are missing something :)");
document.getElementById("name").focus();
}
else if (msg === "") {
alert("You are missing something :)");
document.getElementById("msg").focus();
}
else {
document.getElementById("content").innerHTML += ("<p id='post'>Name :. " + name + "</p><br><p id='post'>Comment :. " + msg + "</p><br><p>" + date + "</p>");
alert("Successfully posted :)");
}
}
And the body part :
<div id="content">
<h1>:. Welcome to the discussion .:</h1>
<br><br>
<p>The topic is : The structure of this website.</p>
<br>
Name/Nickname :.<br><input type="text" value="" id="name" maxlenght="32">
<br>
<p>
Message :.<br><textarea id="msg" cols="40" rows="5"></textarea>
<p>
<input type="button" value="Post" onClick="javascript:post()">
</div>
I get some issues when I press the 'post' button, it shows up the alert even being with or without letters on the 'name' and 'msg' inputs. And I can't see if the 'else' part will work because I can't even pass through the first part :c . I tried everything, but no success, hope someone can give me a light.
This section only gets run once:
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
If you want to recheck the name value when post is called, you should have name be reassigned to document.getElementById("name").value within the post function.
Hi I have an HTML for with 2 buttons
<li>
<!--<input type="button" onclick="getOptions()" value="Click Me!" style="margin-left:156px">-->
<button class="submit" type="button" id="orderTickets" onclick="">Order Tickets</button>
<button class="submit" type="button" id="startAgain" onclick="">Start Again</button>
</li>
Both buttons call the the external script file:
$(document).ready(function()
{
$("#departing").datepicker();
$("#returning").datepicker();
$("button").click(function()
{
var destinationTo = $("#myDestination option:selected").text();
var departingFrom = $("#myDepart option:selected").text();
var departing = $("#departing").val();
var returning = $("#returning").val();
var numAdults = $("#adults option:selected").text();
var numChildren = $("#children option:selected").text();
var travelType = $("#class option:selected").text();
if (departing === "" && returning === "")
{
alert("Please enter your travel dates.");
}
else if (returning === "")
{
alert("Please enter a return date.");
}
else if (departing === "")
{
alert("Please enter a departing date.");
}
else
{
confirm("Please confirm your travel: outward journey from " + departingFrom + " on " + departing + " to " + destinationTo + " returning on " +
returning + " adults " + numAdults + " children " + numChildren + " travelling in " + travelType + " coach " + "?");
}
});
});
I only want the button "orderTickets to run the script. I'm sure I can establish the buttin ID within the script then determine if I want to run it, but not sure how. The other button "startAgain" simply clears the form! Maybe my attempt is not the best solution?
HTML and javascript is not my thing and would appreciate some help with this?
Please use
$("#orderTickets").click(function()
{
.
.
.
instead of
$("button").click(function()
{
.
.
.
A little Ps:
$("#orderTickets") selects by id attribute, if you want to select by class you can use $(".orderTickets")
I would use a submit handler on the form itself and change the type of #orderTickets to submit instead of button. A button with type="button" will not submit a form
This way if user uses keyboard enter you catch the event also and aren't relying on click of a button (which may never occur).
If any of the validation fails just return false to prevent the event completing.
$('#formID').submit(function(){
var errors = false;
/* do your validation making errors= true if anything fails */
return !errors;
});