I have the following jQuery script that I need to execute for a long list of objects.
$("#ID_001").change(function(event) {
event.preventDefault();
if(map.hasLayer(ID_001)) {
$(this).removeClass('selected');
map.removeLayer(ID_001);
} else {
map.addLayer(ID_001);
$(this).addClass('selected');
}
});
What I have done
Using the following resource:
api.jquery.com
jquery-loop-for-script
jquery-for-each-looping-a-list-of-objects
I don't think this is a duplicate question of the above as this include an event handler function.
I have written the following loop but this still doesn't work. I can't understand where is the problem.
var obj = {
"#ID_001": "ID_001",
"#ID_002": "ID_001"
};
$.each( obj, function( key, value ) {
$(key).change(function(event) {
event.preventDefault();
if(map.hasLayer(value)) {
$(this).removeClass('selected');
map.removeLayer(value);
} else {
map.addLayer(value);
$(this).addClass('selected');
}
});
});
Can anyone explain to me where is the problem?
Further details
The script is a part of LeafLet map control buttons. Chrome DevTool show this message of error when I click on #ID_001 element, so I think that the problem is that value variable doesn't get the proper value.
Uncaught TypeError: Cannot create property '_leaflet_id' on string
'L_puntiA'
at m (Util.js:56)
at i.hasLayer (Layer.js:211)
at HTMLInputElement. (mymap_main.js:103)
at HTMLInputElement.dispatch (jquery-3.3.1.slim.min.js:2)
at HTMLInputElement.v.handle (jquery-3.3.1.slim.min.js:2)
As sorted out in the comment your problem is that you define the objects with strings instead of variables.
Instead of:
var obj = {
"#ID_001": "ID_001",
"#ID_002": "ID_001"
};
Use:
var obj = {
"#ID_001": ID_001,
"#ID_002": ID_002
};
Related
Im trying to code a site where the objective is to click on two identical images and it hides the both the images you've managed to match to eachother.
$(document).ready(function(){
var animal1;
var animal2;
$(".memory1").on("click", function(){
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function(){
animal2 = $(this).data('animal');
if (animal1==animal2){
$(this).data('animal').hide();
}
else {
alert("Wrong, Try again!");
}
});
});
so the line where its going wrong is obviously
$(this).data('animal').hide();
But I cant figure out a way to hide both images, or a better way of going about it.. :/
http://jsfiddle.net/4vgfca76/
This doesn't work the way you think it does
$(this).data('animal').hide();
When data is used with one argument, it get's the data attribute, which you should already know as you're doing it a few lines above.
What you get is the string hund etc. and that string doesn't have a hide() method.
You should be using the attributes selector to select the elements with that attribute instead
$(document).ready(function () {
var animal1, animal2;
$(".memory1").on("click", function () {
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function () {
animal2 = $(this).data('animal');
if (animal1 == animal2) {
$('img[data-animal="'+animal1+'"]').hide();
} else {
alert("Fel! Försök igen");
}
});
});
I'm trying to get the jquery loadmask addon to work that will mask elements (for loading content). I'm using knockout.js, and when if I mask an element outside of my viewmodel it works, but I want to mask it upon submitting a POST request, and then unmask when I receive it. I'm getting an "object has no method mask" error from this. I'm not quite sure how to go about setting up an object to access it.
This works, but it's not what I want. I noted in the code where I would like to call mask from
<div id = "register_container">
<div data-bind="visible: register()">
<div id = "register_form"> <!--this is the div I want to mask -->>
<button data-bind="click: submitRegistration">Submit</button>
</div>
</div>
</div>
function MyViewModel(){
self.submitRegistration = function(){
//I want to mask here. When I try it says Object[object object] has no method mask
$.post....{
if(data.result == success){
// andunmask here
}
}
}
}
$("#register_form").mask("Waiting..."); //the masking works when I place it here, but it's always enabled and I want it inside the viewmodel where I noted so it only works when the POST request is in process
That's great and all, but I want to mask something from inside the viewmodel where I noted. How can I accomplish this?
I see several things that could be the problem.
Frist, you're doing assignment as opposed to comparison in the if statement. Use this instead:
if(data.result == success){
or even
if(data.result === success){
Second is the fact that I don't quite understand your code self.submitRegistration(){, which typically looks more like this:
var MyViewModel = function () {
var self = this;
self.submitRegistration = function() {
};
};
Then, if I mock the $.post call, it would work like this:
var MyViewModel = function () {
var self = this;
self.register = ko.observable(true);
self.submitRegistration = function() {
$("#register_form").mask("Waiting...");
// Mock $.post
window.setTimeout(function () {
if (1 == 1) {
// andunmask here
$("#register_form").unmask();
}
}, 3000);
}
};
ko.applyBindings(new MyViewModel());
See this fiddle for a demo.
You could even have Knockout help you find the element to look for:
See this updated fiddle for a demo of that.
// Use the "event" parameter to find the element...
self.submitRegistration = function(data, event) {
$(event.target).closest('#register_form').mask("Waiting...");
Hope it helps.
I'm trying to call a function and not the alert and I thought it was as easy as just doing something like this: FunctionsName(); and delete the alert(''); but it's not working for me :(
Can someone please look at the code I have below and tell me what is wrong ?
Thank you so much!!
<script type="text/javascript">
var comper;
function checkComper() {
var onResponse = function(comperNow) {
if (comper === undefined) {
comper = comperNow;
return;
}
if (comper !== comperNow) {
// show a message to the visitor
alert("New Info Added"); // <--*** I WANT TO TAKE THIS OUT AND CALL $("#append").click(function(e)
comper = comperNow;
}
};
$.get('getlastupdate.php', onResponse);
}
var tid = setInterval(checkComper, 2000);
$(function() {
var $table = $("table.tablesorter");
$("#append").click(function(e) {
e.preventDefault();
$.get('updatetable.php', function(data)
{
$table
.find('tbody')
.html('')
.append(data);
$table.trigger("update", [true]);
});
});
/*........ and so on.... */
</script>
What about changin that :
alert("New Info Added");
to that :
$('#append').trigger('click');
It will simulate a click and trigger the function.
One thing important to distinguish:
alert("New Info Added") is a function. Actually, alert() is a function, being passed the parameter "New Info Added".
$('#append').click(function(e) { is not a function, at least, not in the same way. $('#append') is a jQuery selector function, which selects all elements with an id of "append". $('#append').click() is a function that sets a click event on all elements returned in the selector.
What the whole syntax of $('#append').click(function(e) { means is on its own a syntax error. What you're doing is telling the elements found in the selector what their click function should be. But the function(e) { says that it's the start of the code of the function. That line of code isn't complete until the ending }) - the } closing the function declaration and the ) closing the call to click.
So, you can't simply replace alert("New Info Added"), which is a complete function call, with $('#append').click(function(e) {, because it's a syntax error - you haven't completed the function(e) declaration, nor the click function call. You can trigger the click function, as Karl's answer told you. Or, you can use the shortcut:
$('#append').click()
Note that this is a full proper sentence, and can therefore replace the alert.
I'm trying to run a function twice. Once when the page loads, and then again on click. Not sure what I'm doing wrong. Here is my code:
$('div').each(function truncate() {
$(this).addClass('closed').children().slice(0,2).show().find('.truncate').show();
});
$('.truncate').click(function() {
if ($(this).parent().hasClass('closed')) {
$(this).parent().removeClass('closed').addClass('open').children().show();
}
else if ($(this).parent().hasClass('open')) {
$(this).parent().removeClass('open').addClass('closed');
$('div').truncate();
$(this).show();
}
});
The problem is on line 13 where I call the truncate(); function a second time. Any idea why it's not working?
Edit jsFiddle here: http://jsfiddle.net/g6PLu/
That's a named function literal.
The name is only visible within the scope of the function.
Therefore, truncate doesn't exist outside of the handler.
Instead, create a normal function and pass it to each():
function truncate() { ...}
$('div').each(truncate);
What's the error message do you get?
You should create function and then call it as per requirement
Define the function
function truncate(){
$('div').each(function(){
});
}
Then call the function
truncate();
Another approach is to establish, then trigger, a custom event :
$('div').on('truncate', function() {
$(this).......;
}).trigger('truncate');
Then, wherever else you need the same action, trigger the event again.
To truncate all divs :
$('div').trigger('truncate');
Similarly you can truncate just one particular div :
$('div#myDiv').trigger('truncate');
The only prerequisite is that the custom event handler has been attached, so ...
$('p').trigger('truncate');
would do nothing because a truncate handler has not been established for p elements.
I know there's already an accepted answer, but I think the best solution would be a plugin http://jsfiddle.net/g6PLu/13/ It seems to be in the spirit of what the OP wants (to be able to call $('div').truncate). And makes for much cleaner code
(function($) {
$.fn.truncate = function() {
this.addClass('closed').children(":not('.truncate')").hide().slice(0,2).show();
};
$.fn.untruncate = function() {
this.removeClass('closed').children().show();
};
})(jQuery);
$('div').truncate();
$('.truncate').click(function() {
var $parent = $(this).parent();
if ($parent.hasClass('closed')) {
$parent.untruncate();
} else {
$parent.truncate();
}
});
I'm trying to select all the li tags of the document and check if it hasClassName('yes') so if it has, it will remove it. But I'm having a TypeError: Object [object HTMLLIElement], has no method 'hasClassName' error.
This is the DOM method:
document.observe("dom:loaded", function() {
$(document.body).select('input').each(function(element) {
element.observe('click', function() {
init();
});
init();
});
});
The previous code will take the init function and check the if there are checked inputs and add them the 'yes' class name, but if I un-check those inputs, the class remains.
This is the function that I'm trying to do dynamic (add and remove class 'yes');
function init() {
$(document.body).select('input').each(function(element) {
if (element.checked) {
element.up('li').addClassName('yes');
}
if ($(document.body).select('li').hasClassName('yes')) {
element.removeClassName('yes');
}
})
}
Can you help me solving the last part of this function, so the removeclassname method will work? Thank you.
$(document.body).select('li') returns a collection, not an element, right? I would assume you want:
if (element.hasClassName('yes')) {
element.removeClassName('yes');
}
However, it seems that your logic is flawed -- you are first adding the class if the input is checked, then you are immediately removing it. Are you missing an else? Maybe something more like:
function init() {
$(document.body).select('input').each(function(element) {
if (element.checked) {
element.up('li').addClassName('yes');
}
else {
element.up('li').removeClassName('yes');
}
})
}
Wait a sec - that "select" is going to return an array of elements. The "hasClassName" function is a function on Element directly, not on Array or Enumerable. You're missing an "each()" layer.
$$('li').each(function(li) {
if (li.hasClassName('yes')) li.removeClassName('yes');
});