onclick delete node and decrement counter - javascript

I have this code that I use to append some inputs + a button to delete the added input. I've set a counter to limit the number of added inputs to 5. What I'm trying to reach here is : when I click on the delete button it removes the appended element and decrements the counter
$(function($) {
var i = 1;
$("#btn_add").on("click",addAnotherPool);
function deletePool(){
this.parentNode.remove(this);
i--;
}
function addAnotherPool() {
if (i < 5) {
var html = '<div><input name="srv[]" id="srv_'+i+'" type="text"><button id="btn_del" name="pool_btn_add" onclick="deletePool()">Delete</button></div>';
$("#first_member").append(html);
}
i++;
return false;
}
});
When I run this code I get this error on the console :
Uncaught ReferenceError: deletePool is not defined
Can you please explain to me why this error ? How can I make this work ?

the problem is that deletePool is defined in a function, meaning that it is only a temporary function. you will have to make deletePool take in a argument for the object to delete, than have the html onclick like this:
onclick="deletePool(this)"
here is the deletePool function revised:
function deletePool(elm){
elm.parentNode.remove(elm);
}

There are more than one errors:
var i = 1; // declare global this variable
function deletePool(obj) { // declare global this function and use the this obj passed
obj.parentNode.remove(obj);
i--;
}
$(function () {
$("#btn_add").on("click",addAnotherPool);
function addAnotherPool() {
if (i < 5) {
var html = '<div><input name="srv[]" id="srv_'+i+'" type="text"><button id="btn_del" name="pool_btn_add" onclick="javascript:deletePool(this)">Delete</button></div>';
$("#first_member").append(html);
i++;
}
return false;
}
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<div id="first_member">
</div>
<p><br/></p>
<button id="btn_add" onclick="">btn_add</button>

Related

How to apply keyup() function to different DOM element with different input correctly?

I'm trying to limit different min and max input of the day, month and year input of date of birth. However it seems there's something wrong with "this" in the function. May I know what is the correct and good way to write this function? I tried arrow function but it does not work. Should I use bind? Thank you so much!
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(minDob, maxDob){
if($(this).val() > maxDob){
$(this).val(maxDob);
}
if($(this).val() < minDob){
$(this).val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob(minMonth,maxMonth);
});
$("#dob_day").keyup(function(){
minMaxDob(minDay,maxDay);
});
$("#dob_year").keyup(function(){
minMaxDob(minYear,maxYear);
});
});
You have to pass the jQuery object to the minMaxDob like the following, you have to do this because "this" refers to the currently executing function, since you are calling a helper function "this" no longer refers to the DOM object, but to the function minMaxDob:
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(jqObj, minDob, maxDob){
if(jqObj.val() > maxDob){
jqObj.val(maxDob);
}
if(jqObj.val() < minDob){
jqObj.val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob($(this),minMonth,maxMonth);
});
$("#dob_day").keyup(function(){
minMaxDob($(this),minDay,maxDay);
});
$("#dob_year").keyup(function(){
minMaxDob($(this),minYear,maxYear);
});
});
you forget to pass object.
Every time you call function inside a function, function will read only passed data, not variables or object on top.
Example:
function run(){
x=2;
y=3;
check(x);
//or
check2(x,y);
}
function check(x){
if(x<y){
console.log('in that example you will have a error becouse you are not passing 2nd val')
}
}
function check2(x,y){
if(x<y){
console.log('Yes, x is smaller than Y, we send all necessary data')
}
}
Simple ad 'this' and reconstruct your main function.
Your script below with snippet
$(document).ready(function () {
var minMonth = 1;
var maxMonth = 12;
var minDay=1;
var maxDay=31;
var minYear=1900;
var maxYear=2019;
function minMaxDob(minDob, maxDob,el){
if(el.val()> maxDob){
el.val(maxDob);
}
if(el.val() < minDob){
el.val(minDob);
}
}
$("#dob_month").keyup(function(){
minMaxDob(minMonth,maxMonth,$(this));
});
$("#dob_day").keyup(function(){
minMaxDob(minDay,maxDay,$(this));
});
$("#dob_year").keyup(function(){
minMaxDob(minYear,maxYear,$(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='dob_month' type='text'>

Using a variable inside a input check in JS

The input named alternativa-*** will have the *** changed in the PHP that comes before. I'm not using a form on PHP only a onClick statement calling the respondeQuestao function. But this code seems to not work. Someone have any suggestion.
$(document).ready(function() {
function respondeQuestao(qid,resposta) {
var alternativa = document.getElementsByName('input[name = "aternativa-"' + qid ']:checked').value;
document.getElementById("demo").innerHTML = 5 + 6;
if(alternativa==resposta) {
$("#botao-questao"+qid).hide();
};
if(alternativa!=resposta) {
};
};
})
Defining a function within the jQuery Ready statement limits the accessibility - define it outside of the jQuery Ready statement but call it when you need it.
function respondeQuestao(qid, resposta) {
var alternativa = $("INPUT[name^='alternativa-']:checked").val();
$("#demo").html(5+6);
if (alternativa == resposta) {
$("#botao-questro" + qid).hide()
} else {
//
}
}
Call the function inside jQuery:
$(function() {
respondeQuestao("id", 11);
});
I hope this helps.

Scoping issue with using clearTimeout

I am using setTimeout to run a slideshow. I want to have button to stop it. The markup is:
<h3> Modest Mouse at Fillmore in Miami <h3>
<div>
<img id="photo" src="http://the305.com/blog/wp-content/uploads/2014/05/modestmouse3.jpg" alt= "Modest Mouse at Fillmore">
<span>•</span>
<span>•</span>
<span>•</span>
</div>
<button onclick="stopShow();">Stop</button>
The JS is:
var aSlideShowPics = ["http://the305.com/blog/wp-content/uploads/2014/05/modestmouse3.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmoude7.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmouse8.jpg"
];
// Timer for SlideShow
var i = 0;
function changeSlide() {
var stopShowID;
stopShowID = window.setTimeout(function() {
newPic = aSlideShowPics[i];
$("#photo").attr("src", newPic);
i++;
if (i < aSlideShowPics.length) {
changeSlide(); // recursive call to increment i and change picture in DOM.
} else {
i = 0; // reset loop to keep slideshow going
changeSlide(); // Recursive call on loop end
}
function stopShow() {
window.clearTimeout(stopShowID);
}
}, 3000)
}
changeSlide();
I keep getting a reference error on button click of no stopShow. I've tried putting the clearTimeout function in several places in code but get same error. Perhaps a new set of eyes can see my error. Here is the jsfiddle. Thanks for any input.
Move the stopShow outside of the timeout and outside of changeSlide.
var stopShowID;
function changeSlide() {
stopShowID = window.setTimeout( function(){}, 3000);
}
function stopShow() {
if(stopShowID) {
window.clearTimeout(stopShowID);
stopShowID = null;
}
}
the stopShow() method does not exists at the window level, it only exists within the body of changeSlide(). Directly attach it to window
window.stopShow = function() ...
or pull it out of the closure
var i = 0;
var stopShowId;
function stopShow() {
window.clearTimeout(stopShowID);
}
function changeSlide() {
stopShowID = window.setTimeout(function() {
if (i >= aSlidesShowPics.length - 1)
i = 0;
var newPic = aSlideShowPics[i++];
$("#photo").attr("src", newPic);
changeSlide();
}, 3000);
}
I couldn't launch your jsfidle example, so I update the content of your code, 2 issues raised:
1- Your stopShow was undefined, so I attached it to window scope:
window.stopShow = stopShow;
2- For your ClearTimeout scope issue: your stopShowID variable was inside your function changeSlide: your stopShow was using a local copy. I basically put it as a global variable so both function could have access to it.
var aSlideShowPics = ["http://the305.com/blog/wp-content/uploads/2014/05/modestmouse3.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmoude7.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmouse8.jpg"
];
// Timer for SlideShow
var stopShowID;
var i = 0;
function stopShow() {
window.clearTimeout(stopShowID);
}
window.stopShow = stopShow;
function changeSlide() {
stopShowID = window.setTimeout(function() {
newPic = aSlideShowPics[i];
$("#photo").attr("src", newPic);
i++;
if (i < aSlideShowPics.length) {
changeSlide(); // recursive call to increment i and change picture in DOM.
} else {
i = 0; // reset loop to keep slideshow going
changeSlide(); // Recursive call on loop end
}
}, 3000)
}
changeSlide();
working jsfiddle:
http://jsfiddle.net/fLw2a4vs/44/

JQuery and Javascript fade not working

Jquery and Javascript do strange things. If you look to the code there is a "while" loop. It does 3 loops but only fades the last one (#c2).
Here is my code:
<div style="display:none" id="c0">Element 0</div>
<div style="display:none" id="c1">Element 1</div>
<div style="display:none" id="c2">Element 2</div>
<script>
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(document).ready(function(){
$(cual).fadeIn(time);
});
}
else
exit = true;
count++;
time += 100;
}
</script>
The reason you see this is because the cual variable will hold the value #c3 by the time the callbacks execute. Because cual is defined within a global scope, and not the callback scope, it is not bounded to the callback scoe.
There is a workaround for this, by adding an intermediary function, something like this:
function scheduleFade(count) {
var cual = "#c" + count;
$(document).ready(function(){
$(cual).fadeIn(time);
});
}
while(exit == false) {
if(document.getElementById("c" + count)) {
scheduleFade(count);
} else {
exit = true;
}
count++;
time += 100;
}
The script is loaded after the DOM is loaded on the page, so you don't need to use $(document).ready(). I have tested the following script:
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(cual).fadeIn(time);
}
else
exit = true;
count++;
time += 100;
}
and it works.
(Update based on comments)
The variable cual is overwritten on each loop, but the code inside the ondocumentready event listener is only executed after the DOM is fully loaded. At this point the variable cual is only set to the name of the third element.
You can create an own visibility scope for that variable to make it available inside the event listener callback:
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(document).ready((function() {
var elementToFadeIn = cual;
return function() {
$(elementToFadeIn).fadeIn(time);
}
})());
}
else
exit = true;
count++;
time += 100;
}
Here the variable elementToFadeIn is set inside an immediately-invoked-function, which also returns the event listener callback. That way, the locally defined elementToFadeIn will stay with name passed in on the current loop iteration.
–––––
On the other you are using jQuery, why do need the loop in the first place?
Just include this code at the end of the page (i.e. before the closing BODY tag) and you don't need the ondocumentready event, as all relevant parts of the DOM are loaded right before the closing BODY tag.
var time = 1000;
jQuery( '[id^="c"]' ).fadeIn( time );

JavaScript generated HTML with onClick doesn't trigger function

The script below adds items to an array when you click the link, and generates a list of items as html output. You can see an example here: http://jsfiddle.net/dqFpr/
I am trying to create a function to delete items from the list. Not a difficult task with splice(), but somehow clicking the delete link doesn't trigger the test_function() function.
Can someone tell me what I am doing wrong, or show me another way of triggering the function? Your help is really appreciated ;-)
<script language="javascript">
$(document).ready(function() {
function test_function( number ) {
/* This function is not triggered, nothing works inside here!! */
}
});
var lines = [];
function update_list( lines ) {
var thecode = '';
for(var i = 0; i < lines.length; i++) {
thecode = thecode + lines[i] + ' <a onclick="javascript:test_function('+i+')" href="#">(delete)</a><br />';
}
$('div#display').html(thecode);
}
$('a#new').click(function() {
lines.push('another line');
update_list(lines);
});
</script>
<div id="display"></div>
Add a new line
Because in the text assigned to display's innerHTML, *test_function* is just plain text that is evaluated by the HTML parser. At that point, its scope is global, not within the IIFE passed to $(document).ready(). You can fix that by making the function global:
$(document).ready(function(){
window.test_function = function (number) {
// do stuff
}
....
});
or
var test_function;
$(document).ready(function(){
test_function = function (number) {
// do stuff
}
....
});
Or whatever method you like to get access to the function. But while it is declared inside an anonymous function's scope, you can only get access to it from a function that has a closure to the variables in that scope.

Categories