How can I call a specific page everytime than a event occurs? - javascript

I have this follow code in my javascript.
I call this function when the user click in a specific checkbox and then I just change the image of this checkbox.
the problem is that my ExportaZap are accessed just one time, for example, if a click now in my checkbox, I call ExportaZap.ashx and then change the image of this checkbox. If a click again, he don't pass through my ExportaZap.ashx.
How can I do to call ExportaZap ever than my user click on my checkbox using the function below ?
function Visibilidade(id, imagemBaixa, credenciada) {
$.get("../Action/ExportaZap.ashx", { id: id, imagemBaixa: imagemBaixa, credenciada: credenciada }, function (data) {
if (data != "limite") {
if ($("#" + imagemBaixa).attr("src") == "../tema/default/images/CheckVerde.png") {
$("#" + imagemBaixa).attr("src", "../tema/default/images/CheckCinza.jpg");
}
else if ($("#" + imagemBaixa).attr("src") == "../tema/default/images/CheckCinza.jpg") {
$("#" + imagemBaixa).attr("src", "../tema/default/images/CheckVerde.png");
});
}

Something like this should do the trick:
$(document).ready(function(){
$('input[type=checkbox]').click(function(){
Visibilidade(this.id, imagemBaixa, credenciada);
});
}

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" />

Why is my JQuery function not triggered on a cloned element when the event becomes "true"?

I have been making this form that must enable the back-end user to create new questions for users to answer. The form is cloned and appended to a div (selector #content) successfully after the first .on(click) event, but it won't duplicate the form again if the cloned button is pressed. The .on(change) event applied to my drop-down selection does change the content of respective divs like it is supposed to, but only on the original form.
Here's the JQuery code:
$(document).ready(function () {
$('.addAnswer').on("click", function () {
var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
$clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
$('.removeAnswer').show;
$('#mp').append($clone);
$('.answer:last').each(function () {
$('b:last').empty();
$('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
$('.addAnswer').on("click", function () {
idx++;
});
});
if (idx == 2) {
$('.removeAnswer').show();
}
});
$('.nextq').click(function () {
var newqid = $('#content form:last').index() + 1;
$('.done, .nextq, .remove').hide();
$('#content').append('<hr>');
$('#content').append($('form').html()).attr('class', 'q_' + newqid);
$('.nextq').on("click", function () {
newqid++;
});
$('.done:last, .nextq:last, .remove:last').show();
return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
$('.group').hide();
$('#' + $(this).val() + ':last').fadeIn();
$('button.' + $(this).val() + ':last').fadeIn();
});
});
Because I thought posting the whole HTML template would be a tad bit too much, I provided a JSFiddle for you people.
One extra question for the ones that are feeling kind: In the JQuery code it is seen that the contents of the HTML are being parsed using .html() and appended with .append.(Line 33 on the JSFiddle) As the .on(change) function switches the contents of the divisions it should change, .html() sees those changes and takes those along with it. I'd like the .on(click) function to append the div's content in its original state, unchanged by the changes made beforehand by the back-end user. Any help with this would be much obliged.
In order to have jQuery trigger on new elements you would do something like
$( document ).on( "click", "<your id or class>", function() {
//Do stuff
});

jQuery .click not working in if/else statement

I have a connection to the Foursquare API in my application. The user can type in a box to start searching for venues, or they can click one of two venue links to fill the same select box with one of those two venues. I'm having trouble letting the user click one of either two venues in. Here is my code:
JS:
function venueFormatSelection(venue) {
if ( venue.name && venue.location.address ) {
// if a user starts typing into a box, venue.name and venue.address values will pop up for them to select from. OR in the 'else' case, they can click one of either two links
else {
$("#bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
$("#bigdrop_set_2").click(function () {
return $('#bigdrop_set_2').attr('venue_name_2')
})
}
}
HTML:
<span class="which_venue" id="bigdrop_set" venue_name='foo' venue_data='FOO'><%= link_to(FOOOOO) %></span>
<span class="which_venue" id="bigdrop_set_2" venue_name_2='bar' venue_data_2='BAR'><%= link_to(BARRRR) %></span>
For some reason, the "click to populate" JS only works if just ONE of the 'return' lines is included without the .click function:
return $('#bigdrop_set').attr('venue_name')
What's wrong with the code inside my "else" statement? Thanks!
$(".bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
Should be:
$("#bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
As you are selecting an element with the ID bigdrop_set not an element with the class bigdrop_set. ID's should be unique, in your code you have duplicate bigdrop_set ID's which should be changed.
Also I would suggest binding the click elements on the $(document).ready() function, not in the venueFormatSelection function.
Returning the value from the click function doesn't really make much sense either. Either manipulate the value directly in the function or put it in another function itself, not on the click event.
For example:
function alertVenue(venue) {
alert(venue)
}
$("#bigdrop_set").click(function () {
var venue = $('#bigdrop_set').attr('venue_name')
alertVenue(venue);
})
You have something like
$(".bigdrop_set").click(function () {
return $('#bigdrop_set').attr('venue_name')
})
Did you really mean css class selector .bigdrop_set and then id selector #bigdrop_set.
I found a fix by using a global variable. Doubt it's the cleanest approach, but it's working for now:
$("#bigdrop_set").click(function () {
window.clickVenue = $('#bigdrop_set').attr('venue_name');
$(".bigdrop").select2("val", $('#bigdrop_set').attr('venue_data'));
});
$("#bigdrop_set_2").click(function () {
window.clickVenue = $('#bigdrop_set_2').attr('venue_name_2');
$(".bigdrop").select2("val", $('#bigdrop_set_2').attr('venue_data_2'));
});
function venueFormatSelection(venue) {
if (venue.name && venue.location.address) {
var imageSource = venue.categories[0].icon.prefix.slice(0, -1) + venue.categories[0].icon.suffix;
return "<img src='" + imageSource + "' height='20' width='20' />" + " " + venue.name + " (" + venue.location.address + ")";
}
else {
return window.clickVenue;
}
}

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

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