Javascript .click() not working - javascript

I'm creating a store locator for a website and ive got a tooltip box that displays an email the i want to make a link. this is the html:
<div class="gm_popup">
<span class="address"> Address</span><br>
<span class="city"> City</span><br>
<span class="phone"> 123 456</span><br>
<span class="email"> email#example.com</span><br>
</div>
and this is the js:
jQuery(document).ready(function(){
var old_focus_and_popup = focus_and_popup;
focus_and_popup = function (id){
return_val = old_focus_and_popup (id);
setTimeout(function (){
jQuery("#store_map .gm_popup .email").click(function(){
var text = jQuery(this).text();
document.location = "mailto:" + text.trim();
});
jQuery(".gm_popup .email").css('text-decoration','underline').css('color','#2aa8e0');
}, 200);
return return_val ;
}
});
any idea why this wouldnt be working? after adding some console.logs it seems like its getting as far as the .click but no going inside the function. Thanks

You are registering click event
This won't trigger until any click is done manually.
If you wanna get auto click then try like this after registering click event
jQuery("#store_map .gm_popup .email").click();
or
jQuery("#store_map .gm_popup .email").trigger("click");

Well you have all the events code inside the function, and you never end up calling that function. So I've made some changes, removed the setTimeout, as that was unnecessary. Also, made a call to that function.
<div id="store_map">
<div class="gm_popup">
<span class="address"> Address</span><br>
<span class="city"> City</span><br>
<span class="phone"> 123 456</span><br>
<span class="email"> email#example.com</span><br>
</div>
</div>
jQuery(document).ready(function(){
focus_and_popup = function (id){
//return_val = old_focus_and_popup (id);
jQuery("#store_map .gm_popup .email").click(function(){
var text = jQuery(this).text();
console.log("HERE");
document.location = "mailto:" + text.trim();
});
jQuery(".gm_popup .email").css('text-decoration','underline').css('color','#2aa8e0');
return return_val ;
}
focus_and_popup();
var old_focus_and_popup = focus_and_popup;
});

I wrote for you a snippet that simply works.
jQuery(document).ready(function () {
jQuery(".gm_popup .email").click(function () {
alert('hello');
var text = jQuery(this).text();
document.location = "mailto:" + text.trim();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gm_popup">
<span class="address"> Address</span>
<br>
<span class="city"> City</span>
<br>
<span class="phone"> 123 456</span>
<br>
<span class="email"> email#example.com</span>
<br>
</div>

Related

JQuery or JavaScript - get name of btn clicked

I have a quiz like slideshow that dynamically generates the questions and the list of answer options.
The answer options are of input type button and are generated dynamically from a table. The button name is also dynamically generated. The number of answer options is dymamic.
When a user clicks on an answer option I need to capture the name of the button.
I have tested out several interations of my code but am not successfully capturing the button clicked. Any input, insight is greately appreicated. Code is below. Just a quick callout - the HTML works without issue. I am using AMPSCRIPT for a Salesforce Makreting Cloud pages.
function btnAnswer(){
var btnClicked = $('.slide :button[clicked]');
var btnValue = $(btnClicked).val();
var btnName = $(btnClicked).attr("name");
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="slide">
<p class="question-p">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionBackground'))=%%</p>
<h3 class="question-h3">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'Question'))=%%</h3>
<div id="" class="question">
%%[
SET #answerOptions = BuildRowsetFromString(FIELD(ROW(#quizData,#qNum),'QuestionAnswerOptions'),'|')
SET #answerCount = RowCount(#answerOptions)
FOR #aNum = 1 to #answerCount DO
SET #answer = FIELD(ROW(#answerOptions,#aNum),1)
]%%
<div id="answerOptions">
<input value="%%=TreatAsContent(#answer)=%%" class="button-submit btnAnswer" name="Q%%=V(#qNum)=%%A%%=V(#aNum)=%%" type="button">
</div>
%%[
NEXT #aNum
]%%
<!-- BEGIN HIDE CRCT ANSWER FOR JS VALIDATION -->
<input name="crctAnswer" value="%%=V(FIELD(ROW(#quizData,#qNum),'questionCrctAnswerValue'))=%%" type="hidden">
</div>
<!-- END HIDE CRCT ANSWER FOR JS VALIDATION -->
<!-- HIDE/SHOW BASED ON SELECTION -->
<div id="" class="answer">
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_cancel.png">
<h4 class="answer-h4-incorrect" style="display:none;">You are incorrect.</h4> </div>
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_check.png">
<h4 class="answer-h4-correct" style="display:none;">You are correct!</h4> </div>
<div class="answer-explaination" style="display:none;">
<p class="answer-explaination" style="display:none;"><strong>The correct answer.</strong>%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionCrctAnswerText'))=%%</p>
</div>
</div>
</div>
Try using the jQuery button click handler
$(".btnAnswer").click( function() {
$(this).attr('name');
// or
this.name;
});
I guess you'd use Jquery like this:
$(".btnAnswer").click(function() {
// jQuery way
var btnValue = $(this).val();
var btnName = $(this).attr("name");
// Javascript way
var btnValue = this.value;
var btnName = this.name;
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
});

Load More Button JS - Load new content on page

I'm trying to develop a Load-More button using Javascript calling an API done with PHP.
So far, so good. I can load the new objects in a range i += i + 4 (I load three new comments everytime I press the button).
This is my load-more button:
$(document).ready(function () {
$(".load-more").on('click', function () {
var tab = $(this).data('tab');
var next_page = $(this).data('next-page');
console.log(next_page);
console.log(tab);
$.get($(this).data('url') + '?tab=' + tab + '&page=' + next_page, function (data) {
addNewQuestions($.parseJSON(data));
});
});
});
And for every object loaded I want to print each of these html blocks.
<div class="question-summary narrow">
<div class="col-md-12">
<div class="votes">
<div class="mini-counts"><span title="7 votes">
{if $question['votes_count']}
{$question['votes_count']}
{else}
0
{/if}
</span></div>
<div>votes</div>
</div>
<div {if $question['solved_date']}
class="status answered-accepted"
{else}
class="status answer-selected"
{/if}
title="one of the answers was accepted as the correct answer">
<div class="mini-counts"><span title="1 answer">{$question['answers_count']}</span></div>
<div>answer</div>
</div>
<div class="views">
<div class="mini-counts"><span title="140 views">{$question['views_counter']}</span></div>
<div>views</div>
</div>
<div class="summary">
<h3>
<a href="{questionUrl($question['publicationid'])}" class="question-title" style="font-size: 15px; line-height: 1.4; margin-bottom: .5em;">
{$question['title']}
</a>
</h3>
</div>
<div class = "statistics col-sm-12 text-right" style="padding-top: 8px">
<span>
<i class = "glyphicon glyphicon-time"></i>
<span class="question-updated-at">{$question['creation_date']}</span>
</span>
<span>
<i class = "glyphicon glyphicon-comment"></i>
<span class="question-answers">{$question['answers_count']}</span>
</span>
</div>
</div>
</div>
The problem is that I have several conditions, as {if$question['votes_count']} and I'm struggling because I don't know how get those variables when rendering the html.
Then I found something but I can't figure out how to adapt to my case
On that addNewQuestions I think that a good approach would be:
function addNewQuestions(objects) {
$.each(objects, function (i, object) {
console.log(object);
var lastItem = $('div.active[role="tabpanel"] .question-line:last');
var newLine = lastItem.clone(true);
var newObject = newLine.find('.question-col:eq(' + i + ')');
newObject.find('.question-info-container').attr('data-id', object.publicationid);
newObject.find('.vote-count').html(object.votes);
updateTitleAndLink(newObject.find('.question-title'), object);
lastItem.after(newLine);
});
}
function updateTitleAndLink(questionTitle, object) {
questionTitle.attr('href', questionTitle.data('base-question-url') + object.publicationid);
questionTitle.html(object.title);
}
But nothing happens and I can't figure out why.
Any idea or suggestion?
Kind regards

.innerHTML does not modify content in the page

I've searched other similar questions/answers but no one seems to work for me.
I've tried every single combination (text, innerHTML, jQuery, html) to make it work without success.
Javascript:
if (store.indexOf(nome) > -1) {
if (righe+incrementi < 30) {
posizionamento = store.indexOf(nome);
var incrementa = parseInt(document.getElementById('quantity'+posizionamento).innerHTML);
incrementa ++;
document.getElementById('quantity'+posizionamento).innerHTML = incrementa;
incrementi = incrementi+1;
var settam = document.getElementById('count').innerHTML;
var tipo = document.getElementById(posizionamento).getAttribute('data-tipo');
if (tipo === "water"){
settam++;
document.getElementById('count').innerHTML = settam;
alert(settam); }}}
HTML code:
<div id="conteggio">
<div class="titoli">Elements:</div>
<span style="display: none" id="counttxt">
<span class="conteggio">Count</span>
<span class="count" id="count"></span>
</span>
</div>
I'm getting mad with that, the alert work correctly (shows the right int) but the innerHTML does not change nothing, meanwhile the other works correctly (incrementa ++; [...].innerHTML = incrementa;)
Tested in chrome and safari.
In firefox it change, but after I close the alert it set back the "value" to the previous "value".
What I'm doing wrong?
Remove style="display: none" from
<span style="display: none" id="counttxt">
Try
<span id="counttxt">
<span class="conteggio">Count</span>
<span class="count" id="count"></span>
</span>

Replace div element not working in JQuery?

In my use case I have question title and question text labels. When I press edit button I want replace the labels with Text boxes with question title and question text. Also submit and cancel buttons for edit. In this edit if I press cancel I should replace with original div content. The following code is working until cancel. When I press cancel it is not properly replacing the original content. Also the edit button got disabled. I didn't disable edit button anywhere manually.
JQuery code:
//global variable for question edits
var originalQuestion = "";
//Enables and disables the question elements
//for all questions
$('.questiondiv').on('click', '.edit_question_button', function() {
console.log("In submit edit question text area");
var pageURL = $('#page_url').text();
var loggedUser = $('#logged_user').text();
if (!loggedUser) {
console.log("In answerbutton redirect");
window.location.href = "/login/?redirect="+pageURL;
} else {
console.log("question edit");
title_val = $(this).closest('.question-inner').find('.quest_title_val').text();
question_val = $(this).closest('.question-inner').find('.quest_text_val').text();
console.log("question edit logged in 2");
console.log("Question title value ", title_val);
console.log("Question value ", question_val);
newdiv = "<div class='form-input updated_question'><input name='question_title_val' class='question_title_val' type='text' size='81' value='"+title_val+"' /></div> <br /> <div class='form-input'><textarea name='question_text_val' class='question_text_val' rows='8' cols='80'>"+question_val+"</textarea><br /><div class='form-input'><a type='Submit' id='updatequestion' name='updatequestion' class='btn btn-primary updatequestion'>Update Question</a><a type='Cancel' id='cancelupdatequestion' name='cancelupdatequestion' class='btn btn-primary cancelupdatequestion'>Cancel</a></div></div>";
originalQuestion = $(this).closest('.questiondiv').html()
$(this).closest('.question-inner').replaceWith(newdiv);
}
});
//updates question
//question ID may have to added as
//hidden element in the html
$('.questiondiv').on('click', '.updatequestion', function() {
console.log("In update question button");
var question_id = $(this).closest('li').find('.question_id_val').val();
var quest_title = $(this).closest('.updated_question').find('.quest_title_val').text();
var quest_val = $(this).closest('.updated_question').find('.quest_text_val').text();
console.log(quest_title);
console.log(quest_val);
$.getJSON("/question?question_id="+question_id+"&question_title"+quest_title+"&question_val="+quest_val, function(data) {
console.log("update question Response "+data);
$(this).closest('.updated_question').replaceWith(originalQuestion);
});
//$(this).closest('.answersectiondiv').remove();
});
//cancel updatequestion elements
$('.questiondiv').on('click', '.cancelupdatequestion', function() {
console.log("In cancel update question area");
//console.log("Original question div tag ", originalQuestion)
$(this).closest('.question-inner').replaceWith(originalQuestion); //Again use this to remove only parent container div
//$(this).closest('.questiondiv').find('.edit_question_button').prop( 'disabled' , true );
});
HTML code:
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div class="question-inner">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p class="quest_title_val">{{.QuestionTitle}}</p></h6>
</div>
<p class="quest_text_val">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<a href="/userprofile/{{.UserId}}" ><img src="http://tinygraphs.com/spaceinvaders/Dany?theme=frogideas&numcolors=4&size=220&fmt=svg"/>
</a>
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
[<a class="edit_question edit_question_button" >edit</a>|<a class="delete_question_button" id="deleted" ">delete</a>]<br>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
Could someone help me with this? Thanks

Jquery stop repeat my code with after?

I have a problem with my input and my Jquery :
Basically I have this code :
HTML:
<form id="formUser">
<div class="row">
<div class="small-8">
<div class="row">
<div class="small-6 columns">
<label for="right-label" class="right inline">First name</label>
</div>
<div class="small-6 columns">
<input type="text" name="fisrtName" placeholder="First name">
</div>
</div>
</div>
</div>
<div class="row text-center">
<input type="checkbox" class="check"><label for="checkbox"><p>I accept the review agreement</p></label>
<button type="submit" class="button join">Let's Go !</button>
</div>
</form>
JS :
<script type="text/javascript">
$(function(){
$("#formUser").submit(function(){
if(!$('input[name="fisrtName"]').val()) {
$('input[name="fisrtName"]').addClass("error");
$('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");
}
return false;
});
});
</script>
And I have this
When I click several time on the button... the error class is repeat ..
How can i stop the repeat or incrase the actual class error ?
Maybe you should be doing something like this
$("#formUser").submit(function(){
var $element = $('internal[name="fisrtName]');
// ^ save this much faster ^
// ^ you have spelt firstName wrong also ^
// check val and check next element isn't error
if($element.val() && $element.next().hasClass('error') === false) {
$element.addClass('error').after("<small class='error'>Invalid entry</small>");
} else {
// now remove it if you need to
}
return false;
});
Hope it helps.
You should always cache your elements
By doing this:
$('internal[name="fisrtName');
$('internal[name="fisrtName');
$('internal[name="fisrtName');
You're calling the jQuery function 3 times when you do not need to.
You can use:
if($('input[name="fisrtName"]').find('.error').length==0)
$('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");
Or:
var $firstName = $('input[name="fisrtName"]');
if (!$firstName.hasClass("error")) {
$firstName.addClass("error");
$firstName.after("<small class='error'/>");
}
$firstName.find("small.error").text("Invalid entry");
Try to change your code with this, I have aded the line "$('small.error').remove();"
$.q("#formUser").submit(function(){
if(!$.q('input[name="fisrtName"]').val()) {
$.q('small.error').remove();
$.q('input[name="fisrtName"]').addClass("error");
$.q('input[name="fisrtName"]').after("<small class='error'>Invalid entry</small>");
}
return false;
});

Categories

Resources