Checkbox trigger change event - javascript

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

Related

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

Getting twice the same function

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

HTML <select> JQuery .change not working

Alright I don't see why this isnt working. It seems pretty simple.
Here is my drop-down menu:
<div>
<form>
<select id='yearDropdown'>
<c:forEach var="years" items="${parkYears}">
<option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option>
</c:forEach>
</select>
</form>
</div>
and here is the JavaScript
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});
Right now I just want to get it working so I can add functionality. Thanks!
That code is syntactically correct. Most likely running it at the wrong time.
You'll want to bind the event when the DOM is ready:
Native JS/DOM
window.addEventListener('DOMContentLoaded', () => {
const yearDropDown = document.getElementById('yearDropdown');
yearDropDown.addEventListener('change', () => {
alert(yearDropDown.value)
});
});
jQuery
$(function(){ /* DOM ready */
$("#yearDropdown").change(function() {
alert('The option with value ' + $(this).val());
});
});
Or, use live:
$("#yearDropdown").live('change', function() {
alert('The option with value ' + $(this).val());
});
Or, use delegate:
$(document.body).delegate('#yearDropdown', 'change', function() {
alert('The option with value ' + $(this).val());
});
Or, if you're using jQuery 1.7+:
$("#yearDropdown").on('change', function() {
alert('The option with value ' + $(this).val());
});
Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.
I have tried your code in jsFiffle.
I manually added some years as options.
It works right.
Just bind the .change event in the $(document).ready:
$(document).ready(function(){
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});​
});
Your code is correct and is working for me, see here: http://jsfiddle.net/mobweb/2Skp9/
Are you sure jQuery has been loaded properly?
Not sure if this will help, but you could try this:
$("#yearDropdown").live("change", function () {
alert('The option with value ' + $(this).val());
});

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

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

Javascript variable scope issue with jquery click event

I am trying to assign a series of objects stored in an array to jquery click event handlers.
The problem is , when the event fires, I only ever references the last object in the array.
I have put together a simple example to show the problem:
function dothis() {
this.btns = new Array('#button1', '#button2');
}
// Add click handler to each button in array:
dothis.prototype.ClickEvents = function () {
//get each item in array:
for (var i in this.btns) {
var btn = this.btns[i];
console.debug('Adding click handler to button: ' + btn);
$(btn).click(function () {
alert('You clicked : ' + btn);
return false;
});
}
}
var doit = new dothis();
doit.ClickEvents();
The HTML form contains a couple of buttons:
<input type="submit" name="button1" value="Button1" id="button1" />
<input type="submit" name="button2" value="Button2" id="button2" />
When button1 is clicked, it says "You clicked #Button2"
It seems that both button click handlers are pointing to the same object inside var btn.
Considering the variable is inside the for loop, I cannot understand why.
Any ideas?
You need a function factory to close the loop variable, such as this:
//get each item in array:
for (var i=0; i<this.btns.length; i++) {
$(this.btns[i]).click(function(item) {
return function () {
alert('You clicked : ' + item);
return false;
}
}(this.btns[i]));
}
Another good option is to let jquery help you. Use jQuery.each(). The variable btn here is local to the handler function, and so isn't reused between iterations. This allows you to close it and have it keep its value.
$.each(this.btns, function() {
var btn = this;
$(this).click(function () {
alert('You clicked : ' + btn);
return false;
}
});
within an event handler, 'this' usually refers to the element firing the event, in this case, it would be your button
so the solution to your problem is fairly easy, instead of referencing the btn variable, which lives in a higher scope and gets mutated long before the event handler fires, we simply reference the element that fired the event and grab its ID
$(btn).click(function () {
alert('You clicked : #' + this.id);
return false;
});
Note: if your array contains other selectors that just the ID, this will obviously not reflect that and simply continue to show the ID
Lucky, the click handler (and all other event handlers afaik) take an extra parameter for eventData, useful like so:
$(btn).click(btn, function (event) {
alert('You clicked : #' + event.data);
return false;
});
User an array if you're passing multiple things:
$(btn).click(['foo', 'bar'], function (event) {
alert('this should be "foo": ' + event.data[0]);
alert('this should be "bar": ' + event.data[1]);
return false;
});
you have to use closures for this.
i'm not sure if i remember the correct syntax but you could try this:
$(btn).click(function () {
return function() {
alert('You clicked : ' + btn);
return false;
}
});
maybe you need to change just the click binding:
$(btn).click(function () {
alert('You clicked : ' + $(this).attr('id'));
return false;
});
Your problem is here:
alert('You clicked : ' + btn);
btn retains the value from the last time it was called in the loop. Read the value from the button in the event.
$(btn).data('selector', btn).click(function () {
alert('You clicked : ' + $(this).data('selector'));
return false;
});
http://jsfiddle.net/Mc9Jr/1/

Categories

Resources