I have a bunch of text inputs that are dynamically created through a MySQL query.
At the bottom of my page I have this.. I had to use window.load instead of document.ready as the latter would not work
<script>
$(window).load(function() {
$('.<?php echo $sku; ?>').on('input', function() {
$('.'+$(this).attr('class')).val($(this).val());
});
});
It is my understanding that using .on should relate to both past and present dom objects, but this is not the case.
The (messy) html I'm currently dealing with is
<input type="text" class="mySKU18" id="inputsku" contenteditable="true" onkeydown="if (event.keyCode==13) saveToDatabase2(this,'itemnumber','mySKU18')" onClick="showEdit(this);"></input>
This is generated on the page load, and 'reset' using ajax if a button is clicked.
My issue is with the above script in relation to the html above.
Both HTML's are the same on the initial page load and ajax response.
Right now my solution to get this working is to reinitiate the script at the bottom of my ajax php script.
/// my php
?>
<script>
$('.<?php echo $sku; ?>').on('input', function() {
$('.'+$(this).attr('class')).val($(this).val());
});
</script>
This works and does not provide any console errors, but obviously is not ideal.
Anyone know what could be the issue and how to fix it?
Build your new text input elements like this and they will be in the DOM tree. You can build all of your new elements this way and use appendChild to link them together if you need them to be referenced in the DOM tree.
var text = document.createElement("input");
text.setAttribute('type', 'text')
text.setAttribute('id', 'yourID');
text.setAttribute('name', 'yourName');
text.setAttribute('class', 'yourClass');
text.setAttribute('style', 'yourStyle');
document.getElementById("yourParent").appendChild(text);
Related
i´m building a search system for this petshop software web base, the thing is that i search for a name, than send the name with XMLHttpRequest to php page that execute the query and return me the results and display them at my search page,until here is ok. the information that php page returns to search page goes like this:
<?php
$query = "selec ...
$queryName = mysqli_query...
while($fetchNames = mysqli_fetch_array...
?>
<a class="profile">
<div id="clientInfo"><?php echo $fetchNames[0]; ?></div>
</a>
<?php }
?>`
i try to acess the html class .profile imported on searchpage.php:
`<script>
document.querySelector('.profile').addEventListener('click',function=(){
alert('js code works!');
});
</script>
</body>`
i tryed to import it with the results of php query page right after the end of while loop, even with the window.onload=func... it won't work!
javascript won't work at the imported document, it can't see the class to display the alert. how can i work around this issue?
thanks in advance!
As you have dynamically-generated elements, you'll need to make use of event delegation and target an element that exists on page load, and work down from there. You haven't mentioned any parent elements in your question, so I'll target <body> in my answer, as this always exists on page load.
As you're shifting the eventListener up the hierarchy, you need to ignore clicks other than the desired element. This can be achieved with event.target and .contains():
if (document.querySelector('.profile').contains(event.target)) { }
So your final code would look like:
const body = document.querySelector('body');
body.addEventListener('click', function() {
if (document.querySelector('.profile').contains(event.target)) {
alert('js code works!');
}
})
The above ensures that when you click on your dynamically-generated elements your alert() will fire, but it won't fire when you click on any other element.
I can suggest two different methods. The first one is that you can write javascript codes after the html code. or wait for the document to be loaded using 'document.addEventListener('DOMContentLoaded', ...)'
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.profile').addEventListener('click',function=(){
alert('js code works!');
});
})
Turning the header red isn't what I'm trying to achieve, I was actually trying to run a jQuery code, but this is just to show that (maybe) targeting DOM elements is the problem because a simple alert() works.
Also, the Javascript code that isn't working here does work outside this if statement.
if(!empty($_POST['description'])) {
$query = $con->prepare('insert into tasks (user_id, description) values (?,?)');
$query->execute(array($_SESSION['user_id'], $_POST['description']));
?>
<script>
alert('hi'); //works
document.querySelector('header').style.color = 'red'; //doesn't work
</script>
<?php
}
Your JavaScript code is maybe executed before your header is rendered, be sure to launch this code after your footer.
You may also have more than one header element in your page and your querySelector targets the wrong.
If your script executes prior to the header element being in the DOM, the querySelector will not be able to find it because it does not exist.
Try this to have the script exectute after the entire DOM has been parsed (e.g. everything between <html> ... </html>):
document.addEventListener("DOMContentLoaded", function(){
document.querySelector('header').style.color = 'red';
});
On my site I use jQuery autosize library.
It is used on textareas, and are defined in my javascript.js file, with just:
$(".autosize").autosize();
The problem is that when I want to load new textareas into my site using ajax, I need to write this again in the ajax return. Fx:
<textarea name='something' class='autosize'></textarea>
<script type='text/javascript'>
$(".autosize").autosize();
</script>
Is it not possible for the new textareas inserted into the DOM, to automatically "act" according to the javascript.js file from my header?
FYI, this questions is simplified a lot and the real case is on a much larger scale.
As you are using ajax to add the item then in the global js file you may do something like below.
$(document).ajaxSuccess(function() {
$(".autosize").autosize();
});
Using deprecated DOMNodeInserted listener
$('body').on('DOMNodeInserted', '.autosize', function(e) {
$(".autosize").autosize();
});
So I am making a website for radio streams and was told I should use Jquery and AJAX to load the HTML files into a div on button click so that I wouldn't have to make the user load a completely new HTML page for each radio stream. But I am a bit lost since I am new to this language and I am not entirely sure what I am doing wrong.
Currently I have a index.html page that loads each individual div and loads all the available radio stations in an iframe linking to an HTML file. In this HTML file there are around 40 buttons that each have to link to their own radio stream. On a button press I want said stream to load into the 'radio player' div for a smooth transition.
After trying to google the problem I was told to do this with the following JavaScript code:
$(function(){
$(".538").click(function(){
$("#div3").load("/includes/about-info.html");
});
});
Since each button is also showing its own image file, I tried to add class="538 to each image source so the JavaScript knows what is targeted. Unfortunately it doesn't seem to work at all and I have no clue what to do. I tried to do this in a separate index.js file which unfortunately didn't work, so I tried to use the JavaScript code in the HTML file itself, and this didn't seem to do the trick either.
TL/DR: trying to load HTML code in a div when an image button is clicked.
Is there perhaps a tutorial for this available? I tried to search the web but couldn't find anything at all. If anyone is able to help me out with this problem I'd love you forever.
I think what's happening is that you're working with dynamic elements. More importantly you should never use numbers to start off either a class name or id.
Unless you post a bit more code it's hard to figure out exactly what you're wanting to do.
If you work with dynamic html the click event won't work, because well you need do dynamically bind the event listener.
For that you can use
$('#dynamicElement').on('click', function() {
$(this).find('#elementYouWantToLoadInto').load('/includes/about-info.html');
});
The above code works if the element is nested in the button. If it's an external element then use.
$('#dynamicElement').on('click',function() {
$('#elementYouWantToLoadInto').load('/includes/abount-info.html');
});
You mentioned that this language is a bit new to you; If you're open to a bit of refactoring:
Your main page should have 2 sections:
<div id='myButtons'>
<input type='radio' data-url='/includes/about-info.html' />
<...>
</div>
<div id='myContent'></div>
<script>
$(function() { //jquery syntax - waits for the page to load before running
$('#myButtons').on('click', 'input', function() { // jquery: any click from an input inside of myButtons will be caught)
var button = $(this),
url = button.data('url'),
content = $('#myContent');
content.load(url);
});
</script>
Jquery: http://api.jquery.com/
you can try this
$('#myButtons').on('click', 'input', function() {
$.get("about-info.html", function(data) {
$("#div3").html(data);
});
});
or
$(document).ready(function(){
$(function(){
$(".radio538").click(function(){
$("#div3").load("/includes/about-info.html");
});
});
})
$(document).ready(function(){
$('#radio1').on('click',function(){
#('#loadradiohere').load('/includes/about-info.html');
});
});
Try that code in your .js file. I am still working for a similar project man.
So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();