Click a button 5 times on page load - javascript

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>

Related

Why won't the click listener log the user clicking on the div for the first time but does log every other time?

Background information: I'm dealing with many divs and recording the data-id of the particular div that user has clicked on.
I'm not sure why the click listener doesn't log the very first time I click on a div but it does log every other time.
For example, if I navigate to the page and click on a div, the data-id doesn't get logged at all.
But when I click on another div, it does get logged. If I keep clicking on another div, it does get logged, and so on.
How can I fix it so that whenever I navigate to the page for the first time and click on a div, the data gets logged?
Here's my JS code:
let img = document.getElementsByClassName('item');
let userClicked = function () {
let attribute = this.getAttribute("data-id");
console.log("clicked " + attribute);
}
for(let i = 0; i < img.length; i++) {
img[i].addEventListener('click', userClicked, false);
}
In my view problem is somewhere else. Try checking if any other element overlaps or your JS is loading at right time. You can check sample code here. Paste it in separate html file and it will work perfectly file.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Image</title>
<style>
div {
background-color:#eaeaea;
margin-bottom:5px;
}
</style>
</head>
<body>
<div data-id="1" class="item">1 </div>
<div data-id="2" class="item">2 </div>
<div data-id="3" class="item">3 </div>
<div data-id="4" class="item">4 </div>
<script>
let img = document.getElementsByClassName('item');
let userClicked = function () {
let attribute = this.getAttribute("data-id");
console.log("clicked " + attribute);
}
for (let i = 0; i < img.length; i++) {
img[i].addEventListener('click', userClicked, false);
}
</script>
</body>
</html>

can't add a remove/edit feature to my program

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.

Cordova SQLite plugin only works on first call

I have a cordova app with two pages, the first has a search field and the second displays the results of the first.
The displayResults function
function displayResults(){
var query = localStorage.getItem('search');
var db = window.sqlitePlugin.openDatabase({name:"Store-DB", location: 1});
queryDB(db,query);
}
function queryDB(db,query){
db.transaction(function(tx) {
var queryList = query.split(" ");
var sqlText = "SELECT * FROM DB WHERE item LIKE '%"+queryList[0]+"%'";
for (i = 1; i < queryList.length; i++) {
sqlText += " OR item LIKE '%"+queryList[i]+"%'";
}
tx.executeSql(sqlText, [], querySuccess);
}
);
}
function querySuccess(tx,results) {
var i;
var len = results.rows.length;
//Iterate through the results
for (i = 0; i < len; i++) {
console.log(row);
//Get the current row
var row = results.rows.item(i);
var div = document.createElement("div");
div.style.background = "gray";
div.style.color = "white";
div.innerHTML = row;
document.body.appendChild(div);
}
alert("Finished");
}
Here is the code for the second page:
<link rel="stylesheet" type="text/css" href="css/default.css">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/zepto.js" type="text/javascript"></script>
<script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js" type="text/javascript"></script>
<script src="js/code.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener("deviceready", onDeviceReady(), false);
}
function onDeviceReady(){
displayResults();
}
</script>
</head>
<body onload="onLoad()">
<div id="taskbar">
Home
<a id="username" class="toolbar_item" style="float:right;" href="#"></a>
</div>
The first time you load this page displayResults works just fine, but if you click the link back to the main page and load the second page again the console prints the error ReferenceError: no "undefined" has no property "openDatabase" in other words, the SQLite plugin isn't loading. But, if I make displayResults fire on a button press instead of onload it works every time. What is the explanation for this peculiar behavior?
It seems that sometimes deviceready-event is either not fired at all or fired too early when there are more event handlers of different libraries in place. The second problem caused that the brodysoft-plugin is not loaded properly and assign to the window-object as window.sqlitePlugin property because one event handler dispatched deviceready-event too early. It turned out setTimeout was the answer as it had been here
You can use the onpageshow event for example
$('#idofyourpage').bind("onpageshow",function(){
//Do something
});

Trigger click on a span

I want to click on a SPAN.show-more automatically. When i click on it shows hidden text. Its ID is a random number something like: SPAN#yui_3_9_1_10_1397969703476_624.show-more
I use greaseMonkey.
The page is:
https://espanol.answers.yahoo.com/question/index?qid=20091125151524AAvxaLo
My wrong code is:
var i,
list = document.querySelectorAll(".show-more")
for (i = 0; i < list.length; ++i)
{ list[i].click();
}
Maybe I need to wait until the page is full loaded? Do I need a delay?
did you try this? with onclick() method
var i, list = document.querySelectorAll(".show-more")
for (i = 0; i < list.length; ++i)
{
list[i].onclick();
}
Best regards
You can simply call a onclick() event like this:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Click</title>
</head>
<body>
<span class="show-none">hello</span>
<span onclick="this.style.backgroundColor = '#f47121'" class="show-more">hello</span>
<span onclick="this.style.backgroundColor = '#128239'" class="show-more">hello</span>
<script type="text/javascript" charset="utf-8">
var i, list = document.getElementsByClassName("show-more");
for (i = 0; i < list.length; ++i)
{
list[i].onclick();
}
</script>
</body>
</html>
There is no built-in, cross-browser function or method to cause a click. One of the best cross-browser solutions I use if ever needed can be found here. Althrough, if you're trying to cause a function to fire it would be best to just call the function.
As per Luxelin's suggestion, jQuery would be the easiest alternative. When using jQuery $(element).trigger('click') would fire a cross-browser click event on the element.
Though there is a way which you can use:
element.onclick = function(){ .. };
if( something )
element.onclick(); // call the handler
DEMO

Simple Javascript Gallery

So I'm trying to loop through this array and change an image source every few seconds. Right now I have an onload event calling a setTimeOut method which should change the image 5 seconds after the page has loaded I would think, but it is doing it instantly. What is the problem? Here is my code:
<html>
<head>
<title>Ad Rotaror</title>
<script type="text/javascript">
var i = 0;
var ads = new Array(4);
ads[0]='promo1.gif';
ads[1]='promo2.gif';
ads[2]='promo3.gif';
ads[3]='promo4.gif';
ads[4]='promo5.gif';
function change()
{
if(i > 4)
i = 0;
document.images[0].src = ads[i];
i++;
}
</script>
</head>
<body>
<img src="promo1.gif" onload="setInterval(change(), 5000)" />
</body>
</html>
Change 'change()' to 'change'. You are calling the function immediately.

Categories

Resources