jQuery html() working witn alert in loop - javascript

I am using this code :-
function makeDirectionTabs() {
alert('sdfsf');
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
var i = 0;
jQuery('#fullDirections .adp > div').each(function () {
i = i + 1;
alert(i + jQuery(this).html());
directionContent = jQuery(this).html();
jQuery('#tab' + i).append(directionContent)
});
}
I got div elements in tab1 , tab2 etc.. with alert
But when I remove alert from this code I did not get div elements in tabs Why ?
What I am leaving .. Where Am I wrong ?
Please help Me.
Main problem :-
Loop running fast and html() function is not working. When I use alert in loog then loop stay for alert and html() works. Please tell me resoin or solution for this.

Strange because cannot see any asynchronous request anywhere. But usually, you should use the index param of each loop. See if its changing anything:
function makeDirectionTabs() {
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
jQuery('#fullDirections .adp > div').each(function (i) {
directionContent = jQuery(this).html();
jQuery('#tab' + i).append(directionContent)
});
}

Please see if this helps:
function makeDirectionTabs() {
alert('sdfsf');
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
var i = 0;
var $divs = jQuery('#fullDirections .adp > div');
for(var i=0; i < $divs.length ; i++){
directionContent = jQuery($divs[i]).html();
jQuery('#tab' + i).append(directionContent)
}
}

Related

Multiple $("selectort").click (function () in if then construction not working

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

dynamic attachment of event handler not working

I was just trying a small experiment in js. It's something like this; I have a ul and below that about 5 li, now I attach an event handler for click on the 1st li , using a selector like below:
var elem = $('ul li:nth-child('+ i +')');
Now I add the function funk, like so:
var funk = function() {
return i < 5 ? i++ : i = 0 ;
}
Now what I want to happen is once the first li is clicked, I want the event handler to be attached to the next li, and when I click on the li, the click event should be attached to the li after that and so on ...
Now I have written the following code so far:
var i = 0;
$('document').ready(function(){
str = funk();
console.log(str);
var elem = $('ul li:nth-child('+ i +')');
elem.on('click' , function(){
console.log('logged');
funk();
});
});
var funk = function() {
return i < 5 ? i++ : i = 0 ;
}
Now there are some obvious errors in the code that I am not able to iron out, for some reason the funk() function itself does't function as the I is never incremented.
Can somebody help me attach a dynamic event handler?
FIDDLE HERE
Ae-x.
Your code is correct, the problem is with declaration. Move func definition before it gets called.
The problem is with func function. It is a variable, so it gets declared initially and set to undefined, then all lines will gets executed but func is undefined so it will throw error.
I have created a recursive solution for same. This adds handlers for next list items only on click
$(document).ready(function() {
var i = 1;
addEventHandlerForNextItem(i);
function addEventHandlerForNextItem(num) {
var elem = $('ul li:nth-child(' + num + ')');
elem.on('click', function() {
console.log('element:' + elem[0].textContent);
alert('element:' + elem[0].textContent);
i = i + 1;
addEventHandlerForNextItem(i);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
not the prittest, but heres how i managed to attached the event handler dynamically ::
var i = 1;
var funk = function() {
return i < 5 ? ++i : i = 1 ;
}
changeHanderler = function(){
str = funk();
console.log(str);
var elem = $('ul li:nth-child('+ i +')');
elem.on('click.ga' , function(){
console.log('logged');
elem.off('click.ga');
changeHanderler();
});
}
$('document').ready(function(){
elem = $('ul li:nth-child('+ i +')');
elem.on('click.ga' , function(){
changeHanderler();
console.log('logged');
elem.off('click.ga');
});
});
not pritty but effective , also excessive usage of on() and off() jquery functions , maybe should have gone for the one() function.

How to call a script function with same div name in php?

<p>Success login. You will be redirected in <span class="counter">10</span> second(s).</p>
<p>Wrong username/password. You will be redirected in <span class="counter">10</span> second(s).</p>
<script type="text/javascript">
function countdown() {
var i = document.getElementByClassName('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'login.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>
Before it was id=counter, and it works for one span tag. But I want two tags to share the same function. I tried changing it to getElementByClassName but it doesn't work. Can anyone tell me why?
There is no function getElementByClassName(), but just getElementsByClassName() (Note the plural for element*s*!). This returns a NodeList, which you then have to traverse:
function countdown() {
var i = document.getElementsByClassName('counter');
for( var j=0; j<i.length; j++ ) {
if (parseInt(i[j].innerHTML)<=0) {
location.href = 'login.php';
}
i[j].innerHTML = parseInt(i[j].innerHTML)-1;
}
}
setInterval( countdown,1000);
PS: In your setInterval() you do not need a function expression - just give it a reference to the function itself (without calling it!).
document.getElementsByClassName('counter') will return an array.
'getElements' - So to target an element in that array would be like :
document.getElementsByClassName('counter')[0]
or loop through them :
var counters = document.getElementsByClassName('counter');
for(var i=0, len=counters.length; i<len; ++i) {
counters[i].innerHTML = 'I am content ' +i;
}
Edit : - note the 'getElement s ByClassName' ( plural elements ) as others have pointed out
There's no getElementByClassName(); in Javascript. You should use getElementsByTagName();
Or, use jQuery selector $('.counter'); (need jQuery library).
For more information, look at [this][1].

javascript Remove value from array, array problems

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

Use Javascript string as selector in jQuery?

I have in Javascript:
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
}
How can I continue in jQuery like:
$(function() {
$(vst).'click': function() {
....
}
}
NO, like this instead
$(function() {
$(vst).click(function() {
....
});
});
There are other ways depending on your version of jquery library
regarding to this, your vst must need to be an object which allow you to click on it, and you assign a class or id to the object in order to trigger the function and runs the for...loop
correct me if I am wrong, cause this is what I get from your question.
$(function() {
$(vst).click(function() {
....
}
})
You can use any string as element selector param for jQuery.
Read the docs for more information.
http://api.jquery.com/click/
http://api.jquery.com/
You can pass a String in a variable to the $() just the way you want to do it.
For example you can do:
var id = 'banner';
var sel = '#'+id;
$(sel).doSomething(); //will select '#banner'
What's wrong is the syntax you are using when binding the click handler. This would usually work like:
$(sel).click(function(){
//here goes what you want to do in the handler
});
See the docs for .click()
Your syntax is wrong, but other than that you will have no problem with that. To specify a click:
$(function() {
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
$(vst).click(function (evt) {
...
});
}
})
Note that since vst is changing in the loop, your event code should also be placed in the loop.
EDIT: Assuming you want the same thing to happen for each image and each div, you could also do something like this:
$(function () {
function imgEventSpec($evt) {
// image clicked.
}
function divEventSpec($evt) {
// div clicked.
}
for (var idx = 0; idx < img_arr.length && idx < div_arr.length; idx ++) {
$("#" + img_arr[idx]).click(imgEventSpec);
$("#" + div_arr[idx]).click(divEventSpec);
}
});

Categories

Resources