This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I'm trying to learn how AJAX interaction with jQuery works.
So far I have always worked with multi-page applications and am not very good with JavaScript.
To learn this, I'm creating a small project that implements CRUDs on a MySQL table asynchronously.
I have created two jQuery functions that inject the 'index' and 'create' views into the page.
The problem I have is that the main.js file does not listen to the events that occur in the injected part of the web page.
This is the main html document:
<html>
<head>
<meta charset="utf-8">
<title>MySql AJAX CRUD</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>MySQL CRUD</h1>
<button id="create">Create</button>
<button id="index">Index</button>
<button id="store">Store</button>
<div id="content">
Content goes here...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- jQuery CDN -->
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
This is the 'main.js' file wich is inside a directory called 'js':
// Index
$('#index').click( function() {
$('#content').load("contents/index.php");
});
// Create
$('#create').click( function() {
$('#content').load("contents/create.html");
});
// Store
$('#store').click( function() {
alert('store function is working'); // Test
});
});
And this is the content 'create.html' i inject into the main html page:
<p>Country name:</p>
<input type="text" id="countryName"><br><br>
<p>Short description:</p>
<input type="text" id="shortDesc"><br><br>
<p>Long Description:</p>
<input type="text" id="longDesc"><br><br>
<button id="store">Store</button>
If i click on the button on 'create.html' nothing happens.
If i click on the button on 'index.html' the store function trigger.
Can someone explain me why?
as said before, you are using jquery to set a callback on an item that is not yet loaded in the DOM. To fix it, you can register the callback once 'create.html' is loaded:
// Create
$('#create').click( function() {
$('#content').load("contents/create.html", function(){
// Store
$('#store').click( function() {
alert('store function is working');
});
});
});
Related
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I'm trying to write simple web app in VSCode. I have little misunderstanding. May be its really simple thing, but i don't know why it doesn't work normally like in examples which i saw.
i have js file (script.js)
function getHistory(){
return document.getElementById("history-value").innerText;
}
alert( getHistory());
and my index.html where i'm using div's tags
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
in beginning of course referense to js
<head>
<title>Calculator</title>
<meta charset="utf-8" >
<link rel="stylesheet" href="style.css">
<script src="script.js">
</script>
</head>
But allert are not working. I can't see nothing. If i use
console.log (document.getElementById("history-value").innerText );
it shows null in console window.
Please explain me what's wrong with it?
1) As Java script is loaded before html page so you have to add script tage at bottom of the page in your case as you are taking value of history-value element which you have added after script tag so when script tag is loaded there is no element with id history-value so you will get null. So you have to add this script after this element
index.html
<head>
<title>Calculator</title>
<meta charset="utf-8" >
<link rel="stylesheet" href="style.css">
</head>
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
<script src="script.js"></script>
script.js
function getHistory(){
return document.getElementById("history-value").innerText;
}
alert( getHistory());
The problem is that your <script> tag appears in the <head> section of your document, and when the script loads, the rest of your HTML has not yet been loaded by the browser, so the <p id="history-value"> tag effectively does not yet exist as far as the browser is concerned.
In this case, you should put your <script> tag just before the </body> tag, or at the very least after the <p id="history-value"> tag, so that <p> tag appears before the Javascript attempts to read it.
It looks like the script runs when there is no history-value element.
Are you sure you are running the code after document has been loaded?
Your code work in the following snippet (but I guess is due to the fact that javscript is loaded at the end of the document).
But to make sure you can place into a
document.addEventListener( 'DOMContentLoaded', function( event ) {
// your code here
})
function getHistory(){
return document.getElementById("history-value").innerText;
}
document.addEventListener( 'DOMContentLoaded', function( event ) {
alert(getHistory());
});
<div class="result">
<div class="history">
<p id="history-value">55555</p>
</div>
<div class="output">
<p id="output-value" class="output-value">7777777</p>
</div>
</div>
I have one task, when I open the html page, that html contains javascript under script tag, and under which I have implemented one function called auther(). How can I call this function while opening the html page, I don't want to implement it by using onClick or onLoad, etc. methods from html/javascript.
Means whenever my html gets executed my javascript function should get called itself. Following is my html:
<html>
<head>
<title>Demo</title>
</head>
<body>
<div id="authOps" >
<button onclick="auther();">GET author</button>
//By clicking on this button it is working but I want to execute
//this function when this html get executed
</div>
</body>
<script type="text/javascript">
function auther(){
//some code
}
</script>
</html>
In the above scenario whenever my html page is opened, the javascript function should get executed without any click handling.
Note : I have mentioned html code just for reference purpose, My main purpose just to execute javascript function, how can I achieve this??
There are 2 ways to do this as far as i know,
1:
<html>
<head>
<title>Demo</title>
</head>
<body>
<div id="authOps" >
<button onclick="auther();">GET author</button>
//By clicking on this button it is working but I want to execute
//this function when this html get executed
</div>
</body>
<script type="text/javascript">
function auther(){
console.log("Hi");
};
auther();
</script>
</html>
2:
<html>
<head>
<title>Demo</title>
</head>
<body>
<div id="authOps" >
<button >GET author</button>
//By clicking on this button it is working but I want to execute
//this function when this html get executed
</div>
</body>
<script type="text/javascript">
var thisIsAFunction = function (){
console.log("Hi");
}();
</script>
</html>
You can give a try with both options.
Just call the method in a script block, instead of from the button click
<script>auther(); </script>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
For a project I'm working on I'm adding records to a list. But a button in the added content does not execute the javascript it is supposed to execute.
I've made a scribble out of it - as simple as I could make it - to demonstrate.
The button "some content to click" fires of an alert like I expect. The button 'some other content to click' does not.
I suspect this has to do with the html not being there on load... but I'm clueless on how to solve this.
Anyway... if you guys are willing to help... here is the code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>scribble</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
//<![CDATA[
$(function () {
$('.clickme')
.click(function () {
list = $(this).parents('.container').find('.list');
list.prepend('<div class="record"><button class="record_button">some other content to click</button></div>')
alert('added a record');
});
$('.record_button')
.click(function () {
alert('content clicked');
});
});//]]>
</script>
</head>
<body>
<div class='container'>
<button class='clickme'>add record</button>
<div class='list'>
<div class='record'>
<button class='record_button'>some content to click</button>
</div>
</div>
</div>
</body>
</html>
Try
$('.clickme').on('click',function()..
Listeners don't work for added elements unless you call them like so.
jQuery .on()
Hi I am trying to do a simple thing:
1) create two links in my HTML page 2) When user clicks on link1- I want it to call a server side function that displays "Hello World". But when i click on link1- I am not able to see "Hello World" getting displayed anywhere.
I have tried doing this multiple times with different variations but it is not working. Thanks in advance !!
Here is my code
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('IndexHTML').evaluate()
.setTitle('Simple App')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function doSomething(){
return ContentService.createTextOutput('Hello World');
}
IndexHTML.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<h1>Simple App</h1>
<p>
Click on the buttons to view roles
</p>
<a href = "#" id = "index1" >I am index1</a>
<a href = "#" id = "index2" >I am index2</a>
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
</body>
</html>
JavaScript.html
<!-- Load the jQuery and jQuery UI libraries. -->
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.min.js"></script>
<!-- Custom client-side JavaScript code. -->
<script>
$(document).ready(function() {
$("#index1").click(function() {
google.script.run.doSomething() ;
}
});
});
</script>
Stylesheet.html
<!-- Load the jQuery UI styles. -->
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<!-- Custom styles. -->
<style>
body
{
background-color:red;
}
</style>
You are not seeing "Hello World" displayed anywhere because you have not written any code to display it!
All your code does is run server-side doSomething() function, which returns text output. You need to add a success handler to your google.script.run and specify a callback function to run after the server-side function returns successfully, e.g:
google.script.run.withSuccessHandler(processResult).doSomething();
Then write a processResult() javascript function that accepts server return as first argument and does whatever you need to do with it, i.e.:
function processResult(data) {
console.log(data);
}
See google.script.run reference and HTML Service success handlers reference for more details.
I have working javascript mobile app which I have been trying to restructure (correctly or incorrectly). The index.html file contained one page (using data-role="page") with various <div> elements that I hide and show depending what the user wants to do. I thought I could improve the structure by putting each of these <div> elements each in their own page (still in the index.html file) using data-role again. However, the subsequent pages lose their javascript functionality. I have created a very simple index.html file to demonstrate:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<script type="text/javascript" src="js/jquery-1.9.1.min.js"/></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<div data-role="page" id="mainPage">
<INPUT type="button" id="showPageTwo" value="Show Next Page" />
</div>
<div data-role="page" id="secondPage">
<INPUT type="button" id="showMainPage" value="Show Main Page" />
</div>
<script>
$(document).on("pageshow", "#mainPage", function(e) {
alert("Main page");
$("#showPageTwo").click(function()
{
$("#secondPage").show();
$("#mainPage").hide();
});
});
$(document).on("pageshow", "#secondPage", function(e) {
alert("Second page");
$("#showMainPage").click(function()
{
$("#mainPage").show();
$("#secondPage").hide();
});
});
</script>
</body>
</html>
Main page displays correctly, the alert is displayed $("#showPageTwo").click(function() works. But none of the javascript runs when secondPage loads.
Additionally when secondPage is shown it does not have the styling from jquery.mobile-1.3.2.min.css that mainPage has.
What am I doing wrong or misunderstanding? (This is when running the app in the Eclipse AVD)
Additionally, I would like to know:
Is the way I am trying to restructure my code using data-role="page" good or bad practice? Is there a recommended way to structure "pages" in a mobile app?
I also want to put my custom script(s) in their own .js file(s). Can I only load the script shown in the above code before the </body> tag? Is there any way to load it in the header along with all the other scripts?