How to have Jquery blur trigger on everything except hyperlinks/input buttons - javascript

I'm having a slight issue getting a jquery action to function ideally. Currently everything is working properly on a blur from a particular field, which is called "person_email". The issue is that if the end user does this, and decides to click a hyperlink for example on the rest of the page that jquery from the blur triggers, the user see's this briefly, and then continues to the corresponding link.
Ideally this would work that the blur would only trigger if a hyperlink was not clicked.
var $email = $("#person_email");
var $hint = $("#hint_edit");
$email.on('blur',function() {
$hint.hide; // Hide the hint
$(this).mailcheck({
suggested: function(element, suggestion) {
// First error - Fill in/show entire hint element
var suggestion = "Did you mean: <span class='suggestion'>" +
"<span class='address'>" + "</span>" +
"<a href='#' class='domain'>" + suggestion.address +
"#" + suggestion.domain + "</a></span>?";
$hint.html(suggestion).fadeIn(150);
}
});
});
$hint.on('click', '.domain', function() {
// On click, fill in the field with the suggestion and remove the hint
$email.val($(".suggestion").text());
$hint.fadeOut(200, function() {
$(this).empty();
});
return false;
});
})

I assume you want off
$("a").on("click",function() {
$email.off();
});

Related

Why is my .on("click") function for the AuthorButton only returning my variable every other quote?

Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.
I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...
https://codepen.io/DecisiveIndecisive/pen/KXjXXd
The code in question is the Javascript. Thank You!
$(document).ready(function() {
var url =
"https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";
$("#refreshButton").on("click", function() {
$.getJSON(url, function(json) {
var jsonQuote = json.quoteText;
var jsonAuthor = json.quoteAuthor;
$(".counter").html(jsonAuthor);
$("#authorButton").text("Click to Reveal");
if (jsonAuthor === "") {
$("#refreshButton").trigger("click");
} else {
$(".message").html(jsonQuote);
$("#authorButton").click(function() {
$(this).text(function(i, text) {
return text === "Click to Reveal"
? "- " + jsonAuthor
: "Click to Reveal";
});
});
} //else close
}); //getJSON close
}); //refreshButton Close
});
The problem here is that you're re-binding the click function every time the refresh button is clicked. This means that when it is clicked for the second quote, the same effective function is invoked twice. You can see this in action if you add a log message inside of your #authorButton click handler.
$("#authorButton").click(function() {
$(this).text(function(i, text) {
console.log(text)
return text === "Click to Reveal" ? "- " + jsonAuthor : "Click to Reveal";
});
});
A better option would be to have a hidden element which you can update with the jsonAuthor when you get your json feed. Then have a single #authorButton click handler which shows that hidden element when invoked.
Every time you're loading a new quote, you're adding a new click listener. Then, when you check text === "Click to Reveal", the listener is called x times and the text is updated every time.

bootstrap accordion how to check which panel is active

I am using Bootstrap's accordion widget to contain several forms i.e. each panel contains one form. When the last panel is selected, the data from the other panels is meant to be posted which will be used to graph the data. However, I am unable to get to the posting part as I cannot figure out which panel is currently selected. I know that this has to do with a class of active or inactive, but I don't think bootstrap's accordion supports that functionality unlike jquery accordion.
I am trying to figure out the first part i.e. check if the user has clicked on the last panel. In my HTML code it has an id of #results. Here's a jsfiddle that demonstrates the issue I am facing. It does not seem to trigger the second alert function when the user clicks on the #results tag, not sure why.
Sample javascript code:
$('#accordion').on('show.bs.collapse', function () {
$('#results').click(function () {
alert("works"); //testing purposes
});
});
Why don't you do?
$('#results').click(function (){
alert("clicked");
});
Just remove the accordion function and you'll get the on click event directly
Is this what you want?
Fiddle: Demo
take this outside the on function
$('#results').click(function (){
alert("clicked");
});
This is an old thread but I wanted to post an answer as the expected result is not suggested.
What you need to do here is to handle the currently selected collapse items with the event handler. If you use the this keyword for this, you can access the values of the selected object (For example only one item in the form).
Here you can get the $(".collapse") element.
You can get the index number of the active item with $(this).parent().index().
Likewise, you can get the id of the active item with $(this).attr('id').
Your jQuery structure would be:
$(".collapse").on('show.bs.collapse', function(){
//0,1,2,etc..
var index = $(this).parent().index();
//collapseOne, collapseTwo, etc..
var id = $(this).attr('id')
//alert('Index: ' + index + '\nItem Id: ' + id );
console.log('Index: ' + index)
console.log('Item Id: ' + id)
if(id === 'collapseFour')
{
var username = $('#username').val();
var email = $('#email').val();
var age = $('#age').val();
//here you can check the data from the form
$("#result").html("<p> UserName: " + username + "</p> <p> EMail: " + email + "</p> <p> Age: " + age + "</p>");
}
});
I've included a working example here for you (jsfiddle).
$('#accordion').on('show.bs.collapse', function (accordion) {
var $activeCard = $(accordion.delegateTarget.children);
});
or
$('#accordion').on('show.bs.collapse', function () {
var $activeCard = $(this.children);
});

How to get ID of listview item Clicked. [javascript / jquery / jquery mobile]

I need advice on how to detect which <li> is tap/click by the user, then write the 'ID' of the tap/clicked <li> into Localstorage, then use the saved Localstorage to retrieve data for Detail Page.
I'm new to javascript/jquery, if you can provide some simple example code will be very much appreciated.
I know how to write Localstorage, read Localstorage, get JSON data from server API, generate Loop for Listview with unique ID for each <li>.
What I need is, how to use JS to make <li> clickable (link to Detail Page) and write to Localstorage at the same time.
I have tried:
$('.liClass').click(function() { //block of code to write Localstorage };
But the <li> is not clickable and no key/value written to Localstorage. Not to mention to detect which <li> is clicked (this I have no idea).
Please advice, thank you.
Code update:
//Show restaurant listing - NOTE: This is not first page. Link from other Page.
$('#restaurantList').on("pagebeforecreate", function() {
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
}
);
});
//Listview link to Detail Page
$(document).ready(function(){
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
Also tried:
//Listview link to Detail Page
$('#restaurantList').on("pageload", function() {
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
You don't need to make any <li> element to be clickable by your self, when you add the click event to any element, that will be triggered when the item is clicked.
Your problem will basically be that the element is not loaded when the event is bind to it. So you have to add your code inside document ready event like this.
$(document).ready(function(){
$('.liClass').click(function() {
var id= $(this).attr("id"); // Get the ID
};
});
$('.liclick').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
Working Fiddle
You will need to use the event delegation to assign the click event since you are building the HTML DOM dynamically via JSON request, thus not being able to locate the 'li' elements at the time of the page load. So, it would look like:
$(document).on("click", ".rstList", function (event) {
// click event
}
See this link for more details:
jQuery event delegation
I have solved my problem with the example code provided by stackoverflow member here. My previous problem is because I separate the creation of the listview and bind the click listener in two different page event.
After testing the page event sequence, I'm now putting the click listener into the same page event instead of separate to two. Now my code look like this, hope this will help someone bump into the same problem as me:
//Show restaurant listing
$('#restaurantList').on("pagebeforecreate", function() {
alert('pagebeforecreate event triggered');
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
alert('rstListing() executed');
$('.rstList').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
}
);
});

trigger change event except condition jquery

$('#query_txt').change(function() {
return window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
This event is triggered when it's made a change on input field #query_txt
However I want execute this code unless a user click on this link:
I have tried with this version with coffeescript but is not working:
unless $(".select2-search-choice-close").click()
$('#query_txt').change ->
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val()
How can I do it?
Thank you!
Make a condition flag true when you click it. Or unbind to change in the click handler for your link.
Try this
var buttonClicked = false;
$('#query_txt').change(function() {
if(buttonClicked)
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
$(".select2-search-choice-close").click(function(){
buttonClicked = true;
return false;
});
The fix to this question is in when click on close button and when click on suggestions text with select2.
Select2 returns an object in callback and it is possible check if it's added or removed there. Thank you to Eru.

how to hightlight a div if the page.isvalid=false

I wanna high light particular div when the page.isvalid=false.
on the pageload i am able to get display the error message. But the issue is that i am not able to highlight the control which is required.
I have a js function which sets the error class to the div. Its working fine when i click on a button. On the page load i wanna set this as well.
can i do this using some jquery??? or something other way..
Please let me know how to do this.... share your ideas....
Thanks
yes you can do this by using jquery
$(document).ready(callOnload);
function callOnload() {
//add code to highlight div
//following code is used by me to hightligh input control with has isreqired = true
$("input[isRequired=true]").each(
function(n) {
$('#' + this.id).addClass('mandatory');
if (this.value === '') {
$('#' + this.id).removeClass('normal');
$('#' + this.id).addClass('mandatory');
}
else {
$('#' + this.id).removeClass('mandatory');
$('#' + this.id).addClass('normal');
}
}
);
}

Categories

Resources