Jquery off() and on() when adding options to select - javascript

I have a problem when i add options dinamically to select elements.
I only register the onChange event after add the options, but the event is fired anyway.
I can i prevent this behaviour?
$.each(this.formDependentGroupData, function (index, data) {
el = $("*[dependent-group='" + data.dependentGroup + "']");
el.off('change',function (e) { //** this one
alert('ofchange');
e.stopImmediatePropagation();
if ($(this).val()) {
obj.resetLists($('#' + obj.tableId + "_editorForm"), $(this));
obj.dependentLists($(this), $(this).val());
} else {
obj.resetLists($('#' + obj.tableId + "_editorForm"), $(this));
}
});
el.append(data.options);
if (data.val){
el.val(data.val);
el.on('change',function (e) { //** this one
alert('change');
e.stopImmediatePropagation();
if ($(this).val()) {
obj.resetLists($('#' + obj.tableId + "_editorForm"), $(this));
obj.dependentLists($(this), $(this).val());
} else {
obj.resetLists($('#' + obj.tableId + "_editorForm"), $(this));
}
});
}
});
this add the options el.append(data.options); and the event is registered later, but it is fired.
Thanks in advance

Related

Vanilla JS version of jQuery document on click for links?

Is there a pure JS version of this?
$(document).on('click', 'a[href]', function(event) {
event.preventDefault();
here.change(this);
});
The specific feature I'm looking for is adding event listeners for any link that's created later via JS (AJAX for example).
Modern browsers support matches which makes this a lot easier
document.addEventListener('click', function(event) {
if (event.target.matches('a[href], a[href] *')) {
event.preventDefault();
console.log('works fine')
}
}, false);
document.body.innerHTML = '<span>Click Me!</span><br /><div>not me!</div>';
You could make this more convenient with a simple function
function addEvent(parent, evt, selector, handler) {
parent.addEventListener(evt, function(event) {
if (event.target.matches(selector + ', ' + selector + ' *')) {
handler.apply(event.target.closest(selector), arguments);
}
}, false);
}
Note that closest() is only supported in the latest browsers, there's a polyfill on MDN
This replicates the jQuery behaviour a lot more, and is easier to use, it also sets the value of this correctly
function addEvent(parent, evt, selector, handler) {
parent.addEventListener(evt, function(event) {
if (event.target.matches(selector + ', ' + selector + ' *')) {
handler.apply(event.target.closest(selector), arguments);
}
}, false);
}
/* To be used as */
addEvent(document, 'click', 'a[href]', function(e) {
console.log(this)
});
/* Add a dynamic element */
document.body.innerHTML = '<span>Click Me!</span><br /><div>not me!</div>';
You can attach click event to document. check if event.target .tagName is "A" and if event.target has property .href. It is not clear what expected result of here.change(this) is expected to do from text of Question
function dynamicA() {
var a = document.createElement("a");
a.href = "";
a.textContent = "a";
document.body.innerHTML += "<br>";
document.body.appendChild(a);
}
document.addEventListener("click", function(event) {
event.preventDefault();
if (event.target.tagName === "A" && event.target.href) {
// do stuff
dynamicA();
}
});
<a href>a</a>
I believe this accomplishes what you want:
// for all dom elements on click
document.onclick = function(event) {
var el = event.target; // get what is being clicked on
if(el.hasAttribute('href') && el.tagName == 'a') { // check if it's a link
event.preventDefault();
here.change(this); // what is this?
}
}

How to get value inside .html() in JQuery

I am trying to implement an inline edit of Todo lists. I have this code and I want to be able to get the value inside it.
$(function clickedit() {
$(".a").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
var id_val = $(this).attr('value');
//alert(id_val);
updateVal(currentEle, value, id_val);/**/
});
});
function updateVal(currentEle, value, id_val) {
$(currentEle).html('<input class="thVal" id="aaa" type="text" value="' + value + '" />'); // i want to get the value inside the input
var aaa = $('#aaa').val();
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
alert(aaa);
$.post('includes/edit-task3.php', { task_name: aaa, task_id: id_val}, function() {
$(currentEle).html($(".thVal").val().trim());
alert('in');
//current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
}
});
$(document).click(function () {
$(currentEle).html($(".thVal").val().trim());
});
}
How can I get the current value in the input inside .html()?
I tried, var aaa = $('#aaa').val(); but it does not work.. How can I do this?
Thank you so much for your help.
Don't put your events in a function that is triggered by something else
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
var aaa = $(this).val();
alert(aaa);
$.post('includes/edit-task3.php', { task_name: aaa, task_id: id_val}, function() {
$(currentEle).html($(".thVal").val().trim());
alert('in');
//current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
}
});
Use .find(SELECTOR)
$(currentEle).find('#aaa').val();
Edit: As updateVal function could be invoked many times, you will have multiple ID having same value in the DOM. Make sure the ID must be unique

jQuery click event listener inside keyup event listener

I have a keyup event listener that dynamically creates and adds a new button to the page. Then that button needs another click event listener that depends on data only available inside the keyup listener to do its job.
This is the code I have:
$('.select2-input').on('keyup', function(e) {
var self = $(this);
if (self.prev().text() != 'Uhr') {
return;
}
if ($('.select2-no-results').is(':visible')) {
if (!$('#insertWatch').length) {
$($('Uhr Einfügen')).insertAfter(this);
}
} else {
$('#insertWatch').remove();
}
$(document).on('click', '#insertWatch', function(e) {
alert('Added')
$.post('/insert/watch', { name: self.val() }, function(response) {
$('#supplier_id').prepend($('<option value="' + response + '" selected>' + self.val() + '</option>'));
$('.select2-drop-mask, .select2-drop-active').css('display', 'none');
});
return false;
});
e.stopPropagation();
});
The click event listener does not fire at all when the added button is clicked. I'm unable to figure out why. So to sum this up, alert('Added') never pops up.
Try attaching the even when the element is created.
Something like:
$('.select2-input').on('keyup', function(e) {
var self = $(this);
if (self.prev().text() != 'Uhr') {
return;
}
if ($('.select2-no-results').is(':visible')) {
if (!$('#insertWatch').length) {
$($('Uhr Einfügen')).insertAfter(this).on('click', '#insertWatch', function(e) {
alert('Added')
$.post('/insert/watch', { name: self.val() }, function(response) {
$('#supplier_id').prepend($('<option value="' + response + '" selected>' + self.val() + '</option>'));
$('.select2-drop-mask, .select2-drop-active').css('display', 'none');
});
return false;
});;
}
} else {
$('#insertWatch').remove();
}
e.stopPropagation();
});
Is this what you are looking for? http://jsfiddle.net/leojavier/cp34ybca/
$('.select2-input').on('keyup', function(e) {
var button = "<button class='myButton'>my button</button>";
if ($(this).val() != 'Uhr' && !$('.myButton').length) {
$('body').append(button);
$('.myButton').on('click', function(){
$('i').html('Clicked!');
});
}else if ($(this).val() === 'Uhr'){
$('.myButton').remove();
$('i').html('');
}
});

Disable selected options between 5 selectlists with JQuery

I have 5 selectboxes in my HTML page and I'm trying to disable all the options in the other selectboxes that are already selected, they also have to be re-enabled when they are deselected.
So far I came to this result: Click here for JSFiddle
Using this JQuery
$('.poli').on('keyup change', function () {
$(this)
.siblings('select')
.children('option[value=' + this.value + ']')
.attr('disabled', true)
.siblings().removeAttr('disabled');
});
This however, doesn't work too well, It only selects and disables 1 option at the time...
Any solutions?
You could use:
DEMO
$('.poli').on('keyup change', function () {
var selectedValues = $('.poli').find('option:selected').map(function () {
return this.value ? this.value : null;
});
$('.poli').filter(function () {
return !this.value
}).find('option').each(function () {
$(this).prop('disabled', ~$.inArray(this.value, selectedValues));
});
});
I've updated the fiddle. You need to keep track of the selected options and disable those in the other select boxes:
$('.poli').on('keyup change', function () {
var selected = [];
$(".poli option:selected").each(function () {
if ($(this).val() !== "")
selected.push($(this).val());
});
$(".poli:not(this) option").each(function () {
if (selected.indexOf($(this).val()) > -1)
$(this).prop("disabled", true);
else
$(this).prop("disabled", false);
});
});
This cleans up the disable; I'm working on the enabling code will post in a minute:
$('select').change( function () {
$('select').each(function() {
$(this).siblings('select').children('option[value=' + this.value + ']').attr('disabled', true);
});
});

How to bind click and change event for checkbox

I am adding some checkbox to the page through ajax how to bind the click and change function for these checkboxes
my script is here
$(document).delegate("#filterOptions input[name=inNeedAmountRange]").bind("click change", function () {
var elementValue = $(this).val();
if ($(this).is(':checked')) {
alert('checked : ' + elementValue);
}
} else {
alert('Not checked :' + elementValue);
}
});
Try .on()
Fiddle Demo
$(document).on("click change", "#filterOptions input[name=inNeedAmountRange]", function () {
var elementValue = this.value;
if ($(this).is(':checked')) {
alert('checked : ' + elementValue);
} else {
// ^ remove extra }
alert('Not checked :' + elementValue);
}
});
Event Delegation
Try: http://api.jquery.com/on/
$(document).on("change click", ""#filterOptions input[name=inNeedAmountRange]", function() {
//do something
});
You can replace document with any static container.

Categories

Resources