I've several divs with a email icon.
<div class="icon-send-mail" id="test1#email.com"></div>
<div class="icon-send-mail" id="test2#email.com"></div>
<div class="icon-send-mail" id="test3#email.com"></div>
I want to send an email when the user clicks on that icon.
$( document ).ready( function() {
$('.icon-send-mail').click(function(email) {
var mailto_link = 'mailto:'+email;
var win = window.open(mailto_link,'emailWindow');
});
});
How can this be done?
The input to a click handler is an event object. Within that event object you can get the element that was clicked on and therefore it's id, which in your case holds the email address
$('.icon-send-mail').click(function(event) {
var mailto_link = 'mailto:'+event.target.id;
var win = window.open(mailto_link,'emailWindow');
});
Edit the first line within your function:
/* You were passing the event object! */
var mailto_link = 'mailto:'+this.id;
Custom JQuery vs JavaScript performance benchmark
JavaScript/JQuery
$(document).ready(function(){
$('.icon-send-mail').click(function(event) {
var mailto_link = 'mailto:'+this.id;
var win = window.open(mailto_link,'emailWindow');
});
});
Pure Javascript
window.onload = function () {
var elems = document.getElementsByClassName('icon-send-mail');
for (var i in elems) {
if (elems[i].nodeType == 1) elems[i].addEventListener('click', function (event) {
var mailto_link = 'mailto:' + this.id;
var win = window.open(mailto_link, 'emailWindow');
});
}
};
Bonus CSS
.icon-send-mail {
cursor: pointer;
}
Live Demo
You're on the right track:
$( document ).ready( function() {
$('.icon-send-mail').on('click', function(e) {
var mailto_link = 'mailto:' + $(this).attr('id');
var win = window.open(mailto_link, 'emailWindow');
});
});
You should replace your this line:
var mailto_link = 'mailto:'+email;
with the following line:
var mailto_link = 'mailto:'+($(this).attr('id'));
Hi Call below code inside you Click event
$.ajax({
type: "POST",
url: "Mail.aspx/SendMail",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{ 'body':'" + messageBody + "'," +
"'to': '" + msgTo + "'," +
"'from': '" + msgFrom + "'," +
"'subject': " + msgSubject + "'" +
"}",
dataType: "json",
complete: function (transport) { if (transport.status == 200) $("#formcontainer").html("Success"); else alert("Please try again later"); }
});
and write the mailing code on Code behind
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("me#mydomain.com");
mail.To.Add("u#urdomain.com");
mail.Subject = filename;
mail.Body = "Report";
Attachment attachment = new Attachment(filename);
mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Related
When a new button is created it isn't being picked up by the rest of the code
var topics = ["dog", "cat", "pangolin", "snake", "bird", "emu", "cow", "hedgehog"]
$(document).ready(function () {
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
});
$("button").click(function() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function(response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
});
});
What I'm trying to do is when the user creates a new button, that button will then work like the premade buttons. The premade buttons are supposed to display a few gifs.
What is happening is that after I create the new button, clicking on that button won't even console log the id of that new button.
Your event listener $("#btnAddSubmit").click worked only with already created buttons. That is means your new buttons will be without this listener. If you want to add listeners to the new buttons, you must do something like:
// We are create event listener as a function for convenient use
var onButtonClick = function () {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
// Your code here...
}
}
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// We are remove all button's listeners and at once add new
$("button").off('click').on('click', onButtonClick);
});
// And this code will add your listener as it was originally
$("button").off('click').on('click', onButtonClick);
Be cearful if your buttons have another event listeners. If it exists, you connot use .off(). In that case is correct way will be add listener for a new specific button's id.
Based on your question and the js code provided, i guess this is because the newly added button doesn't get the event.
All events are attached to the dom on page load. The new buttons that are injected to the DOM doesn't get the events. jQuery already did the bindings to DOM elements before the new code was injected. To solve this you have to use '.on() method in jQuery
Something like this
$(document).on('click','your_button_class_here',function(){
dosomething();
});
You're using the ready callback, so all of this runs when the DOM is ready. However, you don't actually create the new button until this ready callback has already run! So when you try to add callbacks with $("button").click(function(){}), you are trying to add that callback to all the buttons on the DOM... but some of the buttons you want to add it to do not exist yet. They won't exists until that first button's click callback is executed! So the first button you make will have the callback attached, but the new ones will not.
Maybe try something like this? I expect something will be wrong with how the value of this works on your click callback, but I think it's a nudge in the right direction.
$(document).ready(function () {
$("#btnAddSubmit").click(function () {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// be wary of what the value of `this` refers to! it might refer to
// the `this` of the scope in which it was defined!
function gifCallback() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function (response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
};
// reference the new button by its ID and add your desired callback
$("#gif").click(gifCallback)
});
});
I am able to display out all the details including the button. However, the main problem is that the when I click the button, nothing happens. It says that BtnRemoveAdmin() is not defined when I inspect for errors. However, I have function BtnRemoveAdmin()?? I have tried to move the function to htmlstring. Nothing works. I am not sure what went wrong.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role,
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
for (var i = 0; i < arr.length; i++) {
htmlstring = '<div class="grid-container">' +
'<div>' + arr[i].userid + '</div>' +
'<div>' + arr[i].employeename + '</div>' +
'<div>' + arr[i].role + '</div>' +
'<div>' + '<button onclick="BtnRemoveAdmin()">Remove</button>' + // 'BtnRemoveAdmin' is not defined
'</div>' ;
$("#name").append(htmlstring);
}
function BtnRemoveAdmin() {
var data = event.data;
removeadmin(data.id);
}
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
All your code is defined inside an IIFE.
That includes BtnRemoveAdmin.
When you generate your JavaScript as a string, it is evaled in a different scope.
BtnRemoveAdmin does not exist in that scope.
Don't generate your HTML by mashing strings together.
Use DOM instead.
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
I use JQuery, and sometimes I get the same problem with plain JS functions not being called.
So I create JQuery functions :
$.fn.extend({
btnRemoveAdmin: function() {
...//Do what you want here
}
});
To call it use :
<button onclick="$().btnRemoveAdmin();"></button>
Hope it helps you !
After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");
I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});
I dont know why this is not working. Im trying to pass data through ajax. Iv used this many times but for some reason its not working. Its returning nothing.
here is the js
$('#contactformbtn').click(function(){
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
var datastring = 'fullname=' + fullname + '&youremail=' + youremail + '&subject=' + subject + '&yourmessage=' + yourmessage;
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: datastring,
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
and this is the php
<?php
require 'core/init.php';
if(isset($_POST)){
$fullname = $_POST['fullname'];
$youremail = $_POST['youremail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
echo $fullname;
}
?>
in chrome im checking the console and im getting 2 errors
Uncaught TypeError: Cannot read property '1' of null
Uncaught TypeError: Cannot read property '3' of null
My full js is this, (just incase the error is not the contact function)
$(document).ready(function(){
$("#download-btn").bind("click", downloadfile);
$(".download-link").hide();
function downloadfile()
{
var dl = $("#dl").val();
var counter = 10;
var interval = setInterval(function(e) {
counter--;
if(counter > 0){
$("#download-btn").html("Your Download will begin in " + counter + " Seconds");
$("#download-btn").attr("disabled", "disabled");
} else {
window.location.href="http://www.forwardfiles.com/get_file.php?i="+dl;
$("#download-btn").hide();
$(".download-status").html("<h3 class='center'>Download is complete</h3>");
clearInterval(interval);
}
}, 1000);
}
$('#contactformbtn').click(function(){
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
var datastring = 'fullname=' + fullname + '&youremail=' + youremail + '&subject=' + subject + '&yourmessage=' + yourmessage;
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: datastring,
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
});
Did you try .serialize?
$('#contactformbtn').click(function(){
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: $("form").serialize(),
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
Check in your HTML code if these values
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
Have defined their id's and not only "name" tags
I got it working, the code i had was fine. the problem was i wasnt running php version 5.3, so i updated it and its working :D. Thanks for you help anyway