Good evening,
I am importing with the method load different form which changes when submit, unfortunately the elements are not recorded by javascript after the use of ajax, I found answers to my prolet but I can not remedy it in square...
My test.php file simply returns a text & submite input with a form ^^
Thank you !
$("#voteform").load("test.php", { });
$(document).ready(function() {
$("#vote").submit(function () {
alert('test');
$("#voteform").load("test.php", {
username: $("#username").val()
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>WorldCube.fr || Votes</title>
<link rel="stylesheet" href="vote.css">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="votesystem center">
<div class="votetitle">
</div>
<div id="voteform" class="voteform">
</div>
</div>
</body>
</html>
It's unclear to me what question you're asking, but if you're saying that your event listeners or selectors aren't working before/due to HTML changes after page load, then you can you a selector like this:
$(document).on("submit", "#vote", function(e){
// your code here
});
The difference here is that by applying the listener to the document then even after content loads, the event listener will be still work as expected.
You'll want to put this JavaScript code in a place that is loaded with the document only once, maybe initially, so that event listeners aren't attached twice.
Related
This question already has answers here:
Is it possible to append to innerHTML without destroying descendants' event listeners?
(13 answers)
Closed 1 year ago.
This isn't so much a problem, since I know the solution, as it is a desire to understand what the problem actually is. Take this minimal example:
document.getElementById("testForm").addEventListener('submit', (event) => {
event.preventDefault();
document.getElementById("main").innerHTML += '<p>submitted</p>';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<title>Title</title>
</head>
<body>
<main id="main" class="main">
<form id="testForm">
<input type="submit" name="submit">
</form>
</main>
</body>
</html>
This is supposed to append "<p>submitted</p>" to #main on submission. On the first click, it works as expected. On the second click, the browser seems to lose my event listener and fall back to the default behavior. It reloads the page with a query.
By slightly modifying the code to add a sibling container and appending to that, we can get this to work as expected.
document.getElementById("testForm").addEventListener('submit', (event) => {
event.preventDefault();
document.getElementById("response").innerHTML += '<p>submitted</p>';
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/style.css">
<title>Title</title>
</head>
<body>
<main id="main" class="main">
<form id="testForm">
<input type="submit" name="submit">
</form>
<div id="response"></div>
</main>
</body>
</html>
So I know the solution, but I don't understand the problem.
When you modify the innerHTML of an element, you are removing all event listeners on its children.
This is because the entire tag must be reparsed, losing event listeners in the process.
In my (rough, condensed) HTML + JS I have this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
</head>
<body>
<div id="frame">
<div id="passepartout">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Kandinsky_-_Mit_Reiter%2C_1912.jpg/420px-Kandinsky_-_Mit_Reiter%2C_1912.jpg"
>
<img id="local" style="width:420px;height:auto;margin:20px;margin-top:20px;position:relative;margin-bottom:0"
src="./420px-Kandinsky_-_Mit_Reiter%2C_1912.jpg">
<div style="width:420px;margin:20px;margin-top:0px;position:relative">This is the title</div>
</div>
</div>
<script>
$(function(){
document.querySelector('#local').onload = function(){
console.log('inside onload')
}
document.querySelector('#local').onerror = function(e) { console.log(e) }
})
</script>
</body>
</html>
in which the onload event fires if attached to the image wit a remote source, and not when attached to the one with the localhost source.
In other words this
document.querySelector('#remote').onload
fires and this
document.querySelector('#local').onload
does not.
Why is that?
It is all about timing:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<img src="Lenna.jpg" id="lenna">
<script>
document.getElementById('lenna').addEventListener('load', () => console.log('lenna'))
window.addEventListener('load', () => console.log('window'))
</script>
</body>
$() from jQuery means to run on window.onload, but your image can be loaded before you whole document is ready. It will never happen again if it is already triggered, before the listener is attached.
Simply moving your code outside $() would solve the problem. It is totally ok to do so because your <script> is at the end of your document.
And I would suggest give up jQuery and use the native DOM APIs instead. It is realy really good.
P.S.:
And yeah, it is ok to have a html 5 document omitting the html tags, as long as it is html 5 instead of xhtml.
The answer to this might be quite easy but I couldn't find a solution since everything seems ok. I'm trying to create a google chrome extension and it has a button like this,
document.getElementById("autof").addEventListener("click", autofill());
function autofill() {
console.log("ENTER");
document.getElementsByName("session[username_or_email]").value = "sylent";
document.getElementsByName("session[password]").value = "abcdefg";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>TWITTER</h1>
<button id="autof">Fill</button>
<script src="twt.js"></script>
</body>
</html>
When you add the event listener to the button, you should pass in the function without actually calling it.
document.getElementById("autof").addEventListener("click", autofill);
Using parenthesis with autofill(), you are assigning the result of calling your function to the click handler:
document.getElementById("autof").addEventListener("click", autofill());
Try this:
document.getElementById("autof").addEventListener("click", autofill);
I'm learning to use event listeners, I wanted to log pressing the "Start" button to the console to make sure the button works but I'm not getting any results when I test the .html file in devtools.
I've verified the index.js name referenced in the .html file is the same
I've tried the source code in the header
I've added the src=index.js jQuery library through Google to the bottom before </body>
I've copied the code to repl.it to try a different environment
JAVASCRIPT:
function startQuiz() {
$('#startButton').click(function(event){
console.log("Keep Going");
});
}
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Herbal Medicine: Adaptogens</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="questions" href="store.html">
</head>
<body>
<div class="container">
<p>Intro to Herbal Adaptogens explaining what they are</p>
<button id="startButton">Start</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
I expect the to see "Keep Going" in the console when I press "start" but instead nothing happens at all.
You have the JQuery click() function inside the startQuiz() function. So it won't work unless the outer function (startQuiz()) is run first. You should put it inside a ready function so that it loads once the page is 'ready'.
Change your javascript to look like this:
$(document).ready(function() {
$('#startButton').click(function(event) {
console.log("Keep Going");
});
});
No need to go with jQuery , you can just use js events.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Log Window</title>
</head>
<body>
<script>
function logMe() {console.log('clicked');}
</script>
<button onclick="logMe()">logMe</button>
</body>
</html>
You should put it inside a Jquery click function. This way it will fire when the document loads.
$(document).ready(function() {
$('#startButton').click(function(event) {
console.log("Keep Going");
}
});
I'm new to a lot of javascript and definitely new to Jade templates. I have figured out how to render a small form (textbox and a button) with a template and I have compiled the javascript file to use on the client. I have been able to read that html template up and put into a div in a consuming web page and it shows correctly.
{
html = template()
document.getElementById("container").innerHTML=html;
}
Here's what I can't figure out:
I want other areas of the consuming web page to be able to subscribe to click events on that button. I'm not clear at all how I can have some kind of event notification on this button so when it is clicked, the listeners will be notified of what was typed in the box when the button was clicked.
At the consuming web page level, I guess I could run some kind of event listener and have subscribers listen and be notified at that level. However, I'd like to be able to look at this as a 'component' and subscribe to events directly on what the template produces...
Long story short, is there any way to add functions like 'addListener' to this button in the template? Since the template just produces a string of html rather than an object I'm a bit at a loss as to how I might do this.
Am I trying to do something that is beyond the scope of templates? What should I be using that will separate my code into a 'component' that can be rendered in it's own page or loaded into a consuming web page, and have events subscribed to?
Thanks for any guidance.
---EDIT---
Here is some code that might show more about what I'm trying to accomplish. This does not work, as expected... I hope it illustrates what I'm after though. Essentially I want the produced code from the template to be an object that I can subscribe to events. I don't think it's possible, but if someone could guide me in another direction that would be great! Thanks
main.html -- shows how I'd like to add listeners to a component
{
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Main Content</title>
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="stylesheet" href="bootstrap-3.3.4-dist/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="bootstrap-3.3.4-dist/css/bootstrap.min.css">
<script src="jquery-2.1.4.js"></script>
<script src="bootstrap-3.3.4-dist/js/bootstrap.min.js"></script>
<script src="jade.js"></script>
<script src="search.js"></script>
<script src="runtime.js"></script>
<script>
$(window).load(function() {
html = search()
alert(html)
document.getElementById('left').innerHTML = html
});
searchListener = function(searchText){
alert(searchText);
}
addSearchListener(searchListener);
</script>
</head>
<body>
<div class="row">
<div id="left" class="col-sm-4">
</div>
<div id="right" class="col-sm-8">
</div>
</div>
</body>
</html>
}
search.html (produced from jade template)
{
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" href="search.css">
<script src="jquery-2.1.4.js"></script>
<script type="text/javascript">
var listeners = [];
function search(){
var searchText = $('#searchText').val();
notifySearchListeners(searchText);
}
function addSearchListener(listener){
listeners.push(listener)
}
function notifySearchListeners(searchText){
for (i = 0; i < listeners.length; i++) {
listener = listeners[i];
listener(searchText);
}
}
</script>
</head>
<body>
<div id="search">
<h3>Search</h3>
<input type="text" id="searchText">
<button onClick="search()">Search</button>
</div>
</body>
</html>
}