This is an extension to this question How to get value from nested HTML tag with Jquery/Javascript
When I execute the following script after the first time, the <h2>-tags get duplicated multiple, though I only want the three values displayed...
so my question is, what is going wrong here?
$(document).ready(function () {
$('.submit').on('click', function () {
$('#newLoanDiv').append('<div id="test"></div>');
$('.results-page').contents().appendTo($('#test'));
setTimeout( function(){
$('.submit').removeAttr('disabled');
$('.sums').find('dl').each(function () {
$('<h2 class="value">' + $(this).find('dd').text() + '</h2>').insertBefore('#test');
});
}, 100 );
});
});
Any help is appreciated...
Try the following. Try $('#test').empty(); to clear data of the #test on every click.
$('.submit').on('click', function () {
$('#newLoanDiv').append('<div id="test"></div>');
$('#test').empty();
$('.results-page').contents().appendTo($('#test'));
setTimeout( function(){
$('.submit').removeAttr('disabled');
$('.sums').find('dl').each(function () {
$('<h2 class="value">' + $(this).find('dd').text() + '</h2>').insertBefore('#test');
});
}, 100 );
});
Related
I'm new with Javascript and Jquery and I'm facing a small problem.
I'm trying to make sure that if a given link exists, hovering over this link will bring up a popup with the fadeToggle().
So I wrote this code that works:
if ($('.link-1')) {
$('.link-1').mouseover(function () {
$('.popup-1').fadeToggle();
})
.mouseout(function () {
$('.popup-1').fadeToggle();
})
}
But, instead of repeating it ten times, I wanted to write a loop, like this:
var number = 0;
while (number < 10) {
var popup = '.popup-' + number;
var link = '.link-' + number;
if ($(link)) {
$(link).mouseover(function () {
$(popup).fadeToggle();
})
.mouseout(function () {
$(popup).fadeToggle();
})
}
number++;
}
But it does not work. Could you help me please ?
I thank you in advance !
Based on your comments, I'd recommend this approach.
Add a data attribute to each link that corresponds with the popup you want to fire. This will look something like this:
<a href='#' class='link-1' data-popup='popup-1'> Link </a>
Then add a hover event to ALL links, that performs an action if it has the data type:
//hover event on all links(assumes anchor tags)
$('a').mouseover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
.mouseout(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
You could also make this a single line function using .hover instead of .mouseover and .mouseout if it fits your use case
**refactoring process is added here:
//start with the original function
$('a').hover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
//consolidate the enter and exit events using .hover()
$('a').hover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
//remove the if statement, because the function firing without a pop up won't result in any effect
$('a').hover(function () {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
})
//substitute the variable directly into the jquery tag
$('a').hover(function () {
$(`'.${$(this).attr('data-popup')}`).fadeToggle();
})
// use an ES6 arrow function to make this a one line function
$('a').hover(() => $(`.${$(this).attr('data-popup')}`).fadeToggle())
//as is, this function won't work, because the arrow function binds the "this" keyword differently.
//Event handlers have an optional parameter that is an event JSON object, so we pass that into the function.
//Because it is a parameter, and is used as a variable we can call event "e" for short
//target is a property of the JSON object 'event' that indicates what specific element is triggering the event
// You can console log "e" to see what other values are baked into the event
$('a').hover((e) => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
//lastly, because we are using an anonymous arrow function with only one parameter, we can omit the parenthesis around the paremeter
$('a').hover(e => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
The end result is the one liner below!
$('a').hover(e => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
Additional info on data attributes can be found here:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
welcome to the web community :-)
My jQuery skills are a bit rusty, but I recall, that there is an Attribute Contains Selector, which you could combine with .each() like so:
$('[class*="link-"]').each(function (index, link) {
$('[class="popup-"' + index + '"]').each(function (_, popup) {
$(link)
.mouseover(function () {
$(popup).fadeToggle();
})
.mouseout(function () {
$(popup).fadeToggle();
})
}
}
The second index is not interesting, that's why I named the argument „_”.
Let me know, whether it still works
If your objects are in order from link-1 to link-10, you can try this method
Loop object that has class "link-[number]" using each function
save number using index + 1
give action to object that have been hovered
so the code will be like this:
$('[class*="link-"]').each(function (index) {
var number = index + 1; //index start from 0, so it need to add + 1
$(this)
.mouseover(function () {
$('[class="popup-' + number+ '"]').fadeToggle();
})
.mouseout(function () {
$('[class="popup-' + number+ '"]').fadeToggle();
})
});
But if your object are not in order from link-1 to link-10, I recommend to use custom data attribute in your HTML code.
Example:
<a class="link-1" data-number="1">test 1</a>
<div class="popup-1" style="display:none">
test 1 popup
</div>
Then change number variable to this code:
var number = $(this).attr("data-number");
It will more save.
Hope it helps.
So I'm trying to make a search using a dropdown list, which will show/hide some checkboxes depending on the chosen answer. The problem is that it works perfectly on jsfiddle.net but refuses to load properly on my local machine. I saw a similar post and said something about adding $(window).load(function()) before the rest of the script, but even then it refused to work. I might be doing something wrong so any help is appreciated.
The link for jsfiddle is this: http://jsfiddle.net/CDyZf/66/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(window).load(function());
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
});
</script>
The argument of load() needs to be a function.
load(function()) would pass it the return value of calling a function called function, if function wasn't a reserved word making it a error.
function init() {
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
}
$(window).load( init );
How can I fix problem with jQuery function ".css" which works only when it is triggred by user (console, button, ...) ?
I'm using interval in .ready function for trigger it but it dosn't work. However .html function is changing the text properly.
$(document).ready(function()
{
setInterval(function()
{
$.get("./getData", function(data)
{
$(".text").html("" + data + " %");
$(".circle").css("border-width", "" + data + "px");
});
}, 1000);
});
Other border properties specified properly? Border color and weight? Its working fine when specified.
Your code looks fine, make sure data is numeric value and you have element with class name circle
jsFiddle
Try to call this function on window.onload.
<script>
function testFunction()
{
setInterval(function()
{
$.get("./getData", function(data)
{
$(".text").html("" + data + " %");
$(".circle").css("border-width", "" + data + "px");
});
}, 1000);
}
window.onload=testFunction;
</script>
I have the following inline javascript, im using a jquery countdown plugin to display time remaining.
this code exists with each "Comment" on the page, hence it is repeating multiple time on the page. How can I make this external? and avoid the repetition?
im using .nt mvc razor and attaching id.
<script type="text/javascript">
$(function () {
var dateLeft = new Date(#(item.UnixTicks));
$('#countdown-#(item.ID)').countdown({until: dateLeft, format:'MS', onExpiry: liftOff, onTick: watchCountdown});
function liftOff() {
alert('We have lift off!');
}
function watchCountdown(periods) {
$('#monitor-#(item.ID)').text('Just ' + periods[5] + ' minutes and ' +
periods[6] + ' seconds to go');
}
});
</script>
You can put the UnixTicks into an attribute in the comment, give all of the comments a class="comment", and loop over them:
$('.Comment').each(function() {
var dateLeft = new Date(parseInt($(this).attr('data-unixticks'), 10));
...
});
$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
hi,i got a problem in my program..... please help me T.T.
above function is not run. i think the clue should be here.
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
})
all ajax part is ok, i think is because dom problem?,
the click() is created before i run the ajax.(i have the action before i got the input) is this causing click function malfunction. any solution for this problem ^^ thx
You should use jQuery live
Yes..for the click function on 'save' button to work...it should be present when page is loaded...try running click after ajax function..it should work fine then..
Even Live function will work --- It will take care of element even if it is added in future.
$('#Save').live('click',function(){
//ur code here
});
But Live will not work on older browsers.
You need to use $.live to workout event handling on elements added dynamically.
$('#save').live('click', function(){ ... });
I think what you are trying to say is that the first bit of code won't work because the second bit of code hasn't run yet. This second bit of code adds the HTML which the first bit works upon.
In which case, try the live() function instead of click()
You need to add the click handler after the object is created. You could just add your existing handler code to the ajax success, after the line where you create the #save element.
Yeap, try putting your $('#save').click inside your ajax callback function.
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
})
try out this...add the function after you add the actual element...
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
})
$(document).ready(function() {
var waterVolume
function initialFill(){
waterVolume = Math.floor(Math.random() * (150000 - 50000 + 1)) + 50000
initialWidth = $('.resizable_tank').width()
initialHeight = $('.resizable_tank').height()
stabilizeWaterPipe(initialWidth,initialHeight)
}
function stabilizeWaterPipe(currentWidth,currentHeight) {
stableHeight = $('.resizable_tank_pipe').offset().top + $('.resizable_tank_pipe').height() + 8
$('.stable_tank_pipe').css({height: (stableHeight-400)+"px", bottom: "-"+(stableHeight-400)+"px"})
stabilizeCalc(currentWidth,currentHeight)
}
function stabilizeCalc(currentWidth,currentHeight) {
stableTankWidth = $('.stable_tank').width()
stableTankHeight = $('.stable_tank').height()
increasedHeight = parseFloat(currentHeight - stableTankHeight)
// im getting problem here with filling and make equal levels of water in both the cylinders would u pls help me with some code .
}
$('.resizable_tank').resizable({
handles: 'e,s,se',
maxWidth: 800,
minWidth: 180,
minHeight: 400,
resize: function(event, ui) {
var currentWidth = ui.size.width;
var currentHeight = ui.size.height;
stabilizeWaterPipe(currentWidth,currentHeight)
}
})
initialFill()
});