I have a server that dynamically(asp.net ) generate webpages that I can't alter.
On all pages I would like to capture all buttons clicked.
In JSFiddle https://jsfiddle.net/forssux/aub2t6gn/2/ is an example..
$(".checkout-basket").click (function ()
The first alert shows the 3 possible values,
but not the chosen item..
$(".button.button-dl").click(function ()
In jsfiddle this part doesn't get executed
Strangely on my real webpage I get the button clicked...but when I put it in the If then construction it fails to console.log the chosen item..
I hope somebody can explain me how to get these..
Kind Regards
Guy Forssman
//$("div.detail-info,table.checkout-basket").click(function () {
// var knopje = $(this).attr("class")//.split(" ");
// console.log(knopje + " knopje was clicked");
// if(knopje.indexOf("detail-info") > -1) {
// console.log("div class detail-info is clicked");
// }
// else if (knopje.indexOf("checkout-basket") > -1) {
// console.log("table class checkout-basket is clicked");
// }
// else {
// alert ("er is op iets anderes gedrukt");
// }
// capture click on download button in checkout-basket page
$(".checkout-basket").click (function () {
basket =[];
item="";
str = $(this).text();
str = str.replace(/\s\s+/g, ' ');
var str = str.match(/("[^"]+"|[^"\s]+)/g);
console.log("Array ",str);
for(var i=0;i<str.length;i++){
if(str[i] === "verwijder"){
console.log("Item= ",str[i+1]);
item = str[i+1];
basket.push(item);}
}
console.log("Basket contains ",basket);
//console.log("idValBasket ",idVal);
var test = idVal.replace(/\$/gi, "_").slice(0,-6);
console.log("test ",test);
var element = test.substr(test.length - 2)-1;
console.log("element ",element);
element=element-1;
item = basket[element];
console.log("Item finaal is ",item);
});
$(".button.button-dl").click(function () {
var addressValue = $(this).attr('href');
console.log("addresValue Basket",addressValue );
var re = /'(.*?)'/;
var m = addressValue.match(re);
console.log (" m basket is ",m);
if (m != null)
idVal = (m[0].replace(re, '$1'));
console.log("idVal Basket",idVal);
});
//This section captures the download in the detail page
$(".button").click(function () {
var downloadItem = document.getElementsByTagName("h1")[0].innerHTML
console.log("addresValue detail",downloadItem );
});
I never use click function, use on(*event*,...) instead:
$(".checkout-basket").on("click", function (){ /* CODE */ });
Check if visually there are a layout over the a layuot (a div, span, etc.)
Maybe a strange question and maybe i got it wrong, but why do you use push ?? if you want to delete an item ? btw also the example isn't working so maybe that is your problem
Related
I've downloaded this script for use conditional fields in forms:
(function ($) {
$.fn.conditionize = function(options) {
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(is_met, $section) {
if (is_met) {
$section.slideDown();
}
else {
$section.slideUp();
$section.find('select, input').each(function(){
if ( ($(this).attr('type')=='radio') || ($(this).attr('type')=='checkbox') ) {
$(this).prop('checked', false).trigger('change');
}
else{
$(this).val('').trigger('change');
}
});
}
}
return this.each( function() {
var $section = $(this);
var cond = $(this).data('condition');
// First get all (distinct) used field/inputs
var re = /(#?\w+)/ig;
var match = re.exec(cond);
var inputs = {}, e = "", name ="";
while(match !== null) {
name = match[1];
e = (name.substring(0,1)=='#' ? name : "[name=" + name + "]");
if ( $(e).length && ! (name in inputs) ) {
inputs[name] = e;
}
match = re.exec(cond);
}
// Replace fields names/ids by $().val()
for (name in inputs) {
e = inputs[name];
tmp_re = new RegExp("(" + name + ")\\b","g")
if ( ($(e).attr('type')=='radio') || ($(e).attr('type')=='checkbox') ) {
cond = cond.replace(tmp_re,"$('" + e + ":checked').val()");
}
else {
cond = cond.replace(tmp_re,"$('" + e + "').val()");
}
}
//Set up event listeners
for (name in inputs) {
$(inputs[name]).on('change', function() {
$.fn.showOrHide(eval(cond), $section);
});
}
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}(jQuery));
I'm trying this because I need to use conditionize() in one of my tabs and when I reload the tab, all works but if I go to other tab and I return to the previous tab(where I need this works), I get that error.
When I change tabs, I'm only reloading one part of the page.
When I load the page this works perfectly, but if I try to call function again from browser console, it tells me that TypeError: $(...)conditionize() is not a function.
I have included the script in header tag and I'm calling it with this script on the bottom of body:
<script type="text/javascript">
$('.conditional').conditionize();
</script>
EDIT:
I have written
<script type="text/javascript">
console.log($('.conditional').conditionize);
setTimeout(function () {console.log($('.conditional').conditionize);}, 2);
</script>
and this print me at console the function, and when 2 milliseconds have passed, it print me undefined
I have found the solution.
Because any reason, the $ object and jQuery object are not the same in my code.
I have discovered it using this on browser console:
$===jQuery
This return false (This was produced because in other JS, I was using the noConflict(), which give me the problem)
Explanation: noConflict()
So I have solved it changing the last line of my JS by:
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}($));
Putting the $ instead of 'jQuery'
So I am working on this but of jQuery that gets the element id through a click event. This then triggers a function that acts like the deprecated .toggle()- it slides an element down on the fist click and slides that element up on the second click. However, there is a bug that causes the element to slide up and down the amount of times that it has been clicked on. For instance, if this is the second time I use the .clickToggle function, the element (table) slides up and down twice before settling, and so on. I suspect it has something to do with the event object, e, tracking the number of clicks-- i.e. I probably shouldn't set id = e.target.id-- but I'm not sure how to fix while still getting the relevant element id that I need.
Here is the relevant clickToggle plug in (courtesy of an answer here on stackoverflow).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
Here is the buggy code that fits the above description.
$(document).click(function(e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/);
//clickToggle the individual table
$('#showTable' + strId).clickToggle(function () {
$('#table' + strId).slideDown();
$('#table' + strId).load('files.php');
},
function () {
$('#table' + strId).slideUp();
});
});//close mousemove function
Any help would be much appreciated. Thanks.
The problem is that you're registering a new click handler for the element each time you invoke clickToggle:
this.click(function() {...
On each subsequent click, you add another handler, as well as invoking all previous handlers. Bleagh.
Better to be straightforward: (DEMO)
var showTable = function($table) {
$table.slideDown();
$table.load('files.php');
$table.removeClass('hidden');
};
var hideTable = function($table) {
$table.slideUp();
$table.addClass('hidden');
};
$(document).click(function (e) {
//get the mouse info, and parse out the relevant generated div num
var id = e.target.id;
var strId = id.match(/\d$/)[0];
var $table = $('#table' + strId);
if ($table.hasClass('hidden')) {
showTable($table);
} else {
hideTable($table);
}
});
I have 2 columns, on the left side a team with users, on the right column, will be displayed the users i have selected. so everything its working but i'm trying to implement a new feature as follow:
I have 2 list level like a tree (only 2 levels). When i click on a user, i'm able to select it sending to the right column. Also, when i click (single click) on the first level (team name), the second level (users) appear as toggle jquery function. i need so, when i double click on a team (level 1) all users on that tree turns selected and go to column on the right side.
Also, when i click on the team (first level) on the right side, all the users get removed back.
My code to add the users jquery current is:
$(document).ready(function () {
var maxAllowed = 10000;
var $selectTable = $("#mytable");
var $selectList = $("#selected_users ul")
$("#max-count").html(maxAllowed);
var getActivated = function () {
var activated = new Array();
$selectTable.find('input[type="checkbox"]:checked').closest("li").each(function () {
var $obj = new Object;
var currentBox = $(this).find('input[type="checkbox"]');
$obj.id = currentBox.val();
$obj.boxid = currentBox.attr("id");
$obj.name = $(this).find("label").text();
activated.push($obj);
});
return activated;
}
var updateActiveList = function () {
// Truncate list
$selectList.html("");
$(getActivated()).each(function () {
$selectList.append("<li><a href='#' class='remove' data-id='" + this.id + "' data-box-id='" + this.boxid + "'>" + this.name + "</li></a>");
});
}
var countActivated = function () {
return getActivated().length;
}
$('#view').click(function () {
allIds = new Array();
getActivated().each(function () {
allIds.push($(this).attr("id"));
});
alert(allIds);
});
$selectList.on("click", "a.remove", function () {
$('#' + $(this).data("box-id")).prop("checked", false);
updateActiveList();
});
$selectTable.on("change", 'input[type="checkbox"]', function (event) {
if ($(this).is(":checked") && countActivated() > maxAllowed) {
event.preventDefault();
console.log("max reached!");
$(this).prop("checked", false);
}
updateActiveList();
});
});
Here's a jsFiddle with working example:
http://jsfiddle.net/muzkle/LMbV3/7/
Thanks all!
EDIT
Hi, i just added a code to separate single click from double click. So when the user single click, will open the tree. now i need when the user double click on the first level, add both (first level and they're childrens to the right side.
Follow code for single and double clicks:
alreadyclicked=false;
$(document).ready(function () {
$('#mytable').on('click', '.toggle', function (ul) {
//Gets all <tr>'s of greater depth
//below element in the table
var findChildren = function (ul) {
var depth = ul.data('depth');
return ul.nextUntil($('ul').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var ul = el.closest('ul'); //Get <tr> parent of toggle button
var children = findChildren(ul);
var el=$(this);
if (alreadyclicked){
alreadyclicked=false; // reset
clearTimeout(alreadyclickedTimeout); // prevent this from happening
}else{
alreadyclicked=true;
alreadyclickedTimeout=setTimeout(function(){
alreadyclicked=false; // reset when it happens
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (ul.hasClass('collapse')) {
ul.removeClass('collapse').addClass('expand');
children.hide();
} else {
ul.removeClass('expand').addClass('collapse');
children.show();
}
return children;
// do what needs to happen on single click.
// use el instead of $(this) because $(this) is
// no longer the element
},300); // <-- dblclick tolerance here
}
return false;
});
});
And new jsFiddle is: http://jsfiddle.net/muzkle/LMbV3/8/
To distinguish different groups I am wrapping each group/section in a wrapper div with class .wrapper
<div class="wrapper">
.
.
</div>
Also I attached a double click event to .wrapper and currently I have made it to alert its inner labels.Just write some additional code to add these labels to the right side like you are currently adding one element on click.Below is the code with jQuery .dblclick() function which attaches a double-click event to .wrapper.
$('.wrapper').dblclick(function(){
$(this).find('label').each(function(){
alert($(this).text());
});
});
Check this fiddle
I am trying to fill an array with strings, the elements that will be added are the HTML of the clicked <\li>, im probably filling it correctly.
My problem is when the user clicks on the checked link again, i want to remove this item from the array
Here is a code sample:
$(document).ready(function(){
var chosen = [];
var chosenCounter = 0;
find("ul").find("li").click(function(){
var checkBox = $(this).find("img").first();
var checkBoxSrc = checkBox.attr("src");
if(checkBoxSrc == "images/unchecked.png"){
checkBoxSrc = "images/checked.png";
checkBox.attr("src",checkBoxSrc);
checkBox = "";
checkBoxSrc = "";
var temp = this.outerHTML;
chosen[chosenCounter] = temp;
chosenCounter ++;
}
if(checkBoxSrc == "images/checked.png"){
checkBoxSrc = "images/unchecked.png";
checkBox.attr("src",checkBoxSrc);
checkBox = "";
checkBoxSrc = "";
for (var j =0; j<=chosen.length; j++){
var tempRemove = this.outerHTML;
chosen.splice( chosen.indexOf( tempRemove ), 1 );
tempRemove = '';
}
}
});
});
I have been trying all functions and ways i found on internet .. but the results doesn't works well, i would be very thankful for a correction and explanation.
Thanks all in advance.
I've gone through an rewritten the code to work much better. There were a number of issues but here is the fixed version that I tested.
Your original code had an if statement and then another if statement. You needed an if and then an else if.
Notice when finding the child element I just use $('img', this) instead of the find operator and first().
Use ID instead of HTML
For debugging there is a console.log statement in there. Remove this so it works in IE.
To add an element to an array use push
No need to loop over splice to remove the item. Just call splice once.
$(document).ready(function () {
var chosenIDs = [];
$("ul li").click(function () {
var checkBox = $('img', this);
var checkBoxSrc = checkBox.attr("src");
var id = $(this).attr('data-id');
console.log(id + ' ' + chosenIDs.length + ' ' + checkBoxSrc);
if (checkBoxSrc == "images/unchecked.png") {
checkBoxSrc = "images/checked.png";
checkBox.attr("src", checkBoxSrc);
chosenIDs.push(id);
}
else if (checkBoxSrc == "images/checked.png") {
checkBoxSrc = "images/unchecked.png";
checkBox.attr("src", checkBoxSrc);
chosenIDs.splice(chosenIDs.indexOf(id), 1);
}
});
});
Can I Clear a event que in javascript?
when I have done one click event and then does another click event the input field gets the value undefined even when it has a value like "newfile.jpg"
I retrieves the values by doing somevariable = $('#cke_104_textInput').val();
but somevariable gets the value undefined.
here is the javascript code:
$(function () {
// Handler for .ready() called.
function changeLink() {
link = $('#cke_104_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/download/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
clearInterval(changelink);
}
}
function changePic() {
link = $('#cke_103_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/show/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_103_textInput').val('');
$('#cke_103_textInput').val(link);
clearInterval(changepic);
}
}
$('#cke_60').live('click', function (event) {
changelink = setInterval(function () {
changeLink()
}, 1000);
});
$('#cke_64').live('click', function (event) {
changepic = setInterval(function () {
changePic()
}, 1000);
});
});
In the code i try to rewrite the content of two input fields.
this has to be done because the files are not in the sites root they are outside of it, and to be able to show or download them on the site the urls need to be in a specific format.
To answer your first line question, yes you can. Take a look at unbind()
You are creating link as a global variable, which means it is clashing with itself.
Change link = $('#cke_104_textInput').val(); to var link = $('#cke_104_textInput').val();.
Also as a side note, you have this code twice:
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
which is redundant and inefficient. You should remove the first line in both cases, because selecting an element (even via ID) is not a free operation.