Getting twice the same function - javascript

I can't figure out what's happening here. When I select the $('#semestre') option, everything works perfectly. Then I select the $('#turma') option and change its value. Everything works. Then, I change the $('#semestre') value again, and everything works. However, when I change again the $('#turma') value, I get the alert twice. And if I do it again, I get three times the alert and so on. What am I missing here?
$(document).ready(function(){
$('.turma').hide();
$('#semestre').change(function(){
if($(this).val() != ''){
$('.options_turma').remove();
$('.turma').show();
$.post('seleciona_turmas.php', {cd_turma: $(this).val()}, function(data){
var item;
data = jQuery.parseJSON(data);
$.each(data.json, function(){
item = "<option class='options_turma' value='" + this['codigo'] + "'>" + this['descricao'] + "</option>";
$('#turma').append(item);
});
$('#turma').change(function(){
if($(this).val() != ''){
alert("OK");
}else{
alert('NULL');
}
});
});
}else{
$('#turma').val('');
$('.turma').hide();
}
});
});
I tried to be clear, but it's a confusing question.

You are binding the change event every time you change the semestre dropdown. Pull the #turma event out of the semestre change event.
Like this
$('#semestre').change(function() {
//Semestre code
});
$('#turma').change(function(){
//Turma code
});

I think that the .change event on #turma tag must be out of .change event on #semestre tag

$('#turma').on('change', function() {
// ....
});

Related

Checkbox trigger change event

I am verifying certain data then I am dynamically checking checkbox and I want to trigger change event of checkbox.
$("#chk").prop("checked", true).trigger("change");
Change event
$("#chk").change(function () {
if ($(this).is(':checked')) {
if (localStorage.getItem('A') == undefined && sessionStorage.getItem('A') == null) {
location.href = "/" + lang.split('-')[0] + "/login.aspx";
}
$("#dvClass").hide();
$("#dvPromoCode").hide();
$("#resultby").empty();
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
else {
$("#dvClass").show();
$("#dvPromoCode").show();
$("#resultby").empty();
$("#resultby").append('<option value="AirAvailability">' + Res.schedule + '</option>');
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
});
but it is not triggering the change event. But same if I execute from console than it works as expected. I want to know what can be issue.
The order of the function is important here.
You have place your change event before setting the checkbox values. Look at the below code.
$("#chk").prop("checked", "checked").trigger("change");
$("#chk").change(function() {
alert("triggered!");
});
The above won't work because when the jquery run for first line, it doesn't have any change event for the checkbox. You can check the same in this Fiddle
Now place your change event function before calling it like below.
$("#chk").change(function() {
alert("triggered!");
});
$("#chk").prop("checked", "checked").trigger("change");
Now you can get the expected result. You can check the same in this Fiddle
Always better to use the on event for the dynamic added elements like below.
$("#chk").on('change', function() {
alert("triggered!");
});
Be you sur you declared the change event before the prop change instr ; see updated answer :
$(function(){
$("#chk").on("change", function() {
console.log(this.checked)
});
$("#chk").prop("checked", true).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="chk" type="checkbox" />

How do I remove an input field after it's being emptied

I am adding input fields on keystroke, by using an example from the answer for this question. This is my example. I was trying in various ways to remove field if user deletes content from it, so that there are always fields that have some content and one last empty field for adding more, but I just can't find a solution.
This is the code:
$(document.body).on("input", ".external-media-input:last", function () {
var inputID = (parseInt($(this).attr('id')) + 1);
$(".input_fields_wrap").append('<div><input class="external-media-input" id="' + inputID + '" name="external_media[]" type="text"/></div>');
});
You can use on('blur') or .on('focusout')
//...
.on('blur', ".external-media-input:not(:last)", function () {
if(!$(this).val()) $(this).remove();
});
JSFiddle
You can use also on('keyup')
$(document.body).on("keyup", ".external-media-input", function(){
if($(this).val() == '')
$(this).remove();
});
here is your fiddle: https://jsfiddle.net/bembvptx/2/
In your style add one more event:
$(document.body).on("input", ".external-media-input", function () {
if (!$(this).val())
{
$(this).remove();
}
});

is(':visible') not working

hey guys i am new to jquery and i was going throught the modal.js code and found the below code:
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
i tried to understand the above code , so i made a fiddle.
now if you see the if conditional in the code :
if ($this.is(':visible')) {
$('input').trigger('focus');
console.log($this + ' ' + 'is visible');
} else {
console.log($this + ' ' + 'invisible');
}
now even if i have the following display rule I.E.
input {
display:none;
}
The if condition still passes , well thats my 1st difficulty . why does the if condition pass ??
my secound difficulty is the line inside the if condition I.E.
$this.trigger('focus');
now even though the if condition passes the input does't get the focus . why ??
Thank you .
I've made some minor chances to your code, and now it all seems to work for me:
$(document).ready(function () {
$target = $('input');
$target.trigger('focus');
$target.one('show.bs.modal', function (showEvent) {
$this = $(this);
console.log($this);
if ($this.is(':visible')) {
$this.focus();
} else {
console.log($this + ' ' + 'invisible');
}
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
});
});
$target.trigger('show.bs.modal');
});
http://jsfiddle.net/v36zoy1g/2/
To focus an element, you don't need fancy code. the .focus() function does the job for you!
And actually, I think that's about it, can't remember anything else I changed to be honest. :p
You haven't cached $(this) on $this.
You can use:
$this = $(this) before you use $this in your code.

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
});
}
);
});

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

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();
});

Categories

Resources