I making a web app that can be used to store contacts. I am having trouble with a feature in which I use a button to either remove or edit a contact. I have tried something like this.
<doctype html>
<html>
<head></head>
<body>
<table>
<thead></thead>
<tbody id='add-to'></tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// holds all the buttons Id's so I can keep track of which button I pressed
var id_hold = []
$(document).ready(function() {
for (var i = 0; i < id_hold; i++) {
// should add print something to the console if any button is clicked
$('#' + id_hold[i]).click(function() {
console.log('clicked button ' + i);
});
}
addIds();
});
function addIds() {
// allows me to add things to the table I made above
var add_to_dom = $('#add-to');
for (var i = 0; i < 10; i++) {
add_to_dom.append('<button id =' + i + '></button>');
}
}
}
</script>
</body>
</html>
My question is how do make Add a feature like this that works? I don't know how to.
thanks
As #user3743222 said you should do a bit of research before asking a question and need to be specific on what you want to achieve. Your posted code doesn't even run because of extra }. Anyway assuming you want to get this working I made some minimal changes to get that working.
<doctype html>
<html>
<head></head>
<body>
<table>
<thead></thead>
<div id='add-to'></div>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// holds all the buttons Id's so I can keep track of which button I pressed
var id_hold = []
$(document).ready(function () {
addIds();
for (var i = 0; i < 10; i++) {
// should add print something to the console if any button is clicked
(function (j) {
$('#' + id_hold[j]).click(function () {
console.log('clicked button ' + j);
});
})(i)
}
});
function addIds() {
// allows me to add things to the table I made above
var add_to_dom = $('#add-to');
for (var i = 0; i < 10; i++) {
add_to_dom.append('<button id =' + i + '>' + i + ' </button>');
id_hold[i] = i;
}
}
</script>
</body>
</html>
Please note that you need to wrap click binding function inside for loop in a self invoking scope to avoid the case where you get the same i value for all the click handlers.
Related
As a task i am going to make traffic lights change in sequence when a button is pushed.I am going to do this by using a variable and adding one to it each time a image is shown therefore the computer knows what image to display next through the use of if and elses however i am not great at javascript and it will not run i have tried in many different environments for example in dreamweaver and notepad ++ but am getting no where here is what i have got :
<HTML>
<head>
<title>Untitled Document</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap(a)">GO</button>
</body>
<script>
var a = 0
function imageswap(a)
{
if (var a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
var a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.png';
var a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.png';
var a==0;
}
}
</script>
</html>
Thank you for reading and i would appreciate anyones help.
edit:
I have taken on feedback and amended my code but when testing it does not show the image i would like instead the little x .
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0
function imageswap()
{
if (a=0) {
document.getElementById('IMAGE').src='red_empty_empty.gif';
a = a + 1;
}
else if (a==1)
{
document.getElementById('IMAGE').src='empty_amber_empty.gif';
a = a + 1;
}
else
{
document.getElementById('IMAGE').src='empty_empty_red.gif';
var a=0;
}
}
</script>
</html>
edit:
I have taken into account some recommendations and now when i click the button the first image is shown followed by the second on a second button press however it fails to display the third image and the first and second image dont always work first time.
<HTML>
<head>
<title>JAVASCRIPT</title>
</head>
<body>
<img id="IMAGE" width="100" height="200"></img>
<button onClick="imageswap()">GO</button>
</body>
<script>
var a = 0;
function imageswap() {
if (a == 0) {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a += 1;
} else if (a == 1) {
document.getElementById('IMAGE').src = 'empty_amber_empty.gif';
a += 1;
} else {
document.getElementById('IMAGE').src = 'red_empty_empty.gif';
a = 0;
}
}
</script>
in you first line var a = 0 you declare your counter (the var a part) and initialise it by assigning the value 0 (the a = 0 part), therefore there's no need to declare the variable again later, you just want to update it by assigning new values
so the statement if (var a==0) would be incorrect syntactically, because you can't check if a variable declaration is 0. you can of course check if the previously declared variable has a value of 0, which would be if (a==0)
same goes when you try to increment the counter value. var a + 1; is wrong, because you can't increment by 1 a declaration. you should instead assign to the existing counter, the value of itself plus 1, so a = a + 1;
finally, when you try to reset the counter, var a==0;, (beside the usual declaration error) remember that == is comparison and = is assignment. You shouldn't check if the counter is 0, you should assign the value 0 to the counter to reset it.
hope it helps
I Apply with in console.log(a).It will show the increment of a\
Apply the var a in globel It will increment on each time of you click
And increment Apply with a +=1 instead of a+1
var a = 0
console.log(a)
function imageswap(){
if (a==0) {
document.getElementById('IMAGE').src='red_empty_empty.png';
a += 1;
console.log(a)
} else if (a==1){
document.getElementById('IMAGE').src='empty_amber_empty.png';
a += 1;
console.log(a)
} else {
document.getElementById('IMAGE').src='empty_empty_red.png';
a =0;
console.log(a)
}
}
<button onclick="imageswap()">GO</button><br>
<img id="IMAGE" width="100" height="200"></img>
Ok Few things you need to take care:
You are passing a within the function imageswap(a) and you are accessing a from the value passed within the function that'll be 0 all the time. Check https://jsfiddle.net/aegwj88g/
You are checking var a==0, var a==1 which is incorrect. It should be like if(a==0) or else if(a==1).
You are trying to assig value to a with var a + 1 which is also incorrect. Left hand side must be a valid variable other than the javascript tokens (check JS naming convention) which stores the value. it should be a=a+1 (or a+=1) just as you do in maths;
Check this fiddle:
I have something really basics here. I have a button, the idea is to click it so that it adds one field at a time dynamically. But when the page load, I want it to click the button automatically to place 5 fields by default and then afterwards I should still be able to add extra field if necessary.
This is what I so far have, but it adds 5 fields as soon as I click it. I don't want that.
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
</head>
<body>
<div id="container"></div>
<button id="somebutton">Click</button>
<script type="text/javascript">
$(document).ready(function() {
for (var counter = 0; counter < 5; counter++) {
$("#somebutton").click(function () {
$("#container").append('<div class="module_item"><input type="text" /></div>');
});
}
});
</script>
</body>
</html>
Please note that this is the only way how I want it. On page load, button gets clicked automatically 5 times to add 5 fields. Then I can manually click it afterwards to add a sixth, seventh, and so on field.
Just a minor reorganization to your code:
$(document).ready(function() {
$("#somebutton").click(function () {
$("#container").append('<div class="module_item"><input type="text" /></div>');
});
for (var counter = 0; counter < 5; counter++) {
$("#somebutton").click();
}
});
Please note that jQuery .click(function) function only sets a click listener, not calling the function being passed to. However, this function without parameter (i.e. .click()) fires a click event which subsequently calls the callback function.
In your case, a simple solution would be:
$(document).ready(function() {
var clickFunc = function () {
$("#container").append('<div class="module_item"><input type="text" /></div>');
}
$("#somebutton").click(clickFunc);
for (var counter = 0; counter < 5; counter++) {
clickFunc();
}
});
The easiest approach might be to simply add your module sections automatically and then wire up an event handler to add more of them as the button is clicked as seen below :
$(function() {
// Add your five modules initially
for (var counter = 0; counter < 5; counter++) {
AddModuleToContainer();
}
// When your button is clicked, add another module
$("#somebutton").click(AddModuleToContainer);
});
function AddModuleToContainer(){
$("#container").append('<div class="module_item"><input type="text" /></div>');
}
Example
$(function() {
// Add your five modules initially
for (var counter = 0; counter < 5; counter++) {
AddModuleToContainer();
}
// When your button is clicked, add another module
$("#somebutton").click(AddModuleToContainer);
});
function AddModuleToContainer(){
$("#container").append('<div class="module_item"><input type="text" /></div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<button id="somebutton">Click</button>
I am new to coding with js, and have tried many different ways to loop this code, as well as asking a friend of mine who is a bit more proficient than I am, and he was incorrect as well. I looked up how to use loops in js as well, and I seem to be stumped, so if you could also give me a basic explanation as to how loops in js work, that'd be great!
ORIGINAL CODE
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
The original code itself works fine, but it never seems to work with any loops I use.
Most Recent Loop Attempt
- Note: failed, obviously
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
for (i = 0; i < 30; i++) {
text += “The number is ” + i + “<br>”;
}
Thank you in advance!
- Michael
Any tips to just generally improve the code would also be appreciated.
Still can't work out exactly what you're after (looks like: trying to automate some repetitive task in some page for which you don't control the source)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<title>JS Loop Example?</title>
<script>
function foo() {
var div = $("#x")[0];
div.innerHTML = "foo was clicked";
for (i = 0; i < 5; i++) {
div.innerHTML += "<br />!";
}
setTimeout(function(){ $('.barButton').click() }, 3000)
}
function bar() {
var div = $("#x")[0];
while (div.firstChild) {
div.removeChild(div.firstChild);
}
var wibble = document.createTextNode('bar was clicked');
div.appendChild(wibble);
for (i = 0; i < 5; i++) {
div.appendChild(document.createElement('br'));
wibble = document.createTextNode('?');
div.appendChild(wibble);
}
setTimeout(function(){ $('.fooButton').click() }, 3000)
}
</script>
</head>
<body onload='setTimeout(foo, 3000)'>
<script>
// Up until the close of the body, I can just write into the document.
document.write('<div id="x" class="stuffGoesHere">');
document.write('some random text<br />');
for (i = 0; i < 5; i++) {
document.write('#<br />');
}
document.write('</div>');
document.write('<input type="button" class="fooButton" value="foo" onClick="foo()" />');
document.write('<input type="button" class="barButton" value="bar" onClick="bar()" />');
</script>
</body>
</html>
I use jQuery Colorbox which works well like so:
$(function(){
$("a.slideshow").colorbox();
});
Now, if after page load, I add a new node (matching a.slideshow), (created or ajax'ed), then of course it does not work untile I call .colorbox() again.
I have looked around and seen the difficulty with doing this kind of thing generally. (e.g. Is there a JavaScript/jQuery DOM change listener?, http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMSubtreeModified)
So, just in case there's a special solution for Colorbox, I am formally asking the question.
Can't you re-initialise the colorbox at the point of dynamically adding a new element?
So,
$.colorbox.remove();
$("a.slideshow").colorbox();
The following code works for me in Chrome using the DOMSubtreeModified event. You can click on the images as they're added.
<html>
<head>
<link rel="stylesheet" href="./colorbox.css">
</head>
<body>
<div id="myContainer">
</div>
<script type="text/javascript" src="./jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./jquery.colorbox-min.js"></script>
<script type="text/javascript">
$(function() {
var x = 1;
function doColorbox() {
$('.gallery').colorbox({ opacity:0.5 , rel:'group1' });
}
$('#myContainer').bind("DOMSubtreeModified", doColorbox);
var timer = setInterval(function() {
$("#myContainer").append("<a class='gallery' href='./" + x + ".png'>Image " + x + "</a>");
x++;
if (x > 5) {
clearInterval(timer);
}
},3000);
});
</script>
</body>
</html>
The approach could be delegating events, thus no matter if an element not exists at the moment, the event will be attached when the element is created.
https://learn.jquery.com/events/event-delegation/
http://www.jacklmoore.com/colorbox/
Here I will simulate an ajax response and it creates some elements:
//delegates the "click" event to document and namespace the event with ".nsPopup"
$(document).off(".nsPopup").on("click.nsPopup", ".open-box", function(e) {
e.preventDefault();
var item = $(this).data("item");
//the element with ".open-box" class opens the colorbox
//and display the content of a hidden element
$.colorbox({
html: $(".toShow-" + item).html(), //hidden element
width: 100,
height: 80,
fixed: true,
open: true,
overlayClose: false
});
});
//suppose we generate elements via ajax
function ajaxSuccess (data) {
data = [1,2,3,4,5];
var i = 0, max = data.length;
while(i < max) {
$("<div/>")
.append($("<a href='#' class='open-box'/>").text("link " + data[i]).data("item", i+1))
.append($("<div style='display:none'/>")
.append($("<span/>").addClass("toShow-" + (i+1)).text("Hidden " + data[i])))
.appendTo("body");
i += 1;
}
}
//simulates the success response
ajaxSuccess();
I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'