Here is my php/javascript code. I have tried to write the script inside the loop but it doesn't work. This generates two buttons, one for local team, while processing local team, and the second for road team, while processing road team. These buttons show information contained in a div of a different class. For some reason, it works only for the local team, which its the first iteration of the loop.
I have read a lot about people using id's instead of classes, but this is not my case. I am quite lost.
Thank you very much for your help.
<script>
$(".showavgloc").click(function(){
event.preventDefault();
$(".averageloc").slideToggle("slow");
});
$(".showavgvis").click(function(){
event.preventDefault();
$(".averagevis").slideToggle("slow");
});
</script>
<?php
foreach ($teams as $team) {
if ($page=="game") {
if ($team==$locteam) {
echo "<button class='showavgloc'>Show average player</button>";
}
if ($team==$visteam) {
echo "<button class='showavgvis'>Show average player</button>";
}
}
if ($team==$locteam) {
echo "<div class='averageloc' style='display:none'>This div has to be shown/hidden for local team</div>";
}
if ($team==$visteam) {
echo "<div class='averagevis' style='display:none'>This div has to be shown/hidden for road team</div>";
}
}
?>
Try to do this:
after that php code, and before close it ( before this "?>"), do an "echo" that contains:
<script>
$(".showavgloc").click(function(){
event.preventDefault();
$(".averageloc").slideToggle("slow");
});
$(".showavgvis").click(function(){
event.preventDefault();
$(".averagevis").slideToggle("slow");
});
</script>
and try to use it as you want. This might help in some cases, because when you use the jQuery library and then you generate html throw code, the DOM keeps with the "initial" version an jQuery can't work properly because never find the controls. The right order is : Print controls and then bind jQuery events.
Good luck
Your code seems to work fine when everything is included:
$(".showavgloc").click(function(){
event.preventDefault();
$(".averageloc").slideToggle("slow");
});
$(".showavgvis").click(function(){
event.preventDefault();
$(".averagevis").slideToggle("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class='showavgloc'>Show average player</button>
<button class='showavgvis'>Show average player</button>
<div class='averageloc' style='display:none'>This div has to be shown/hidden for local team</div>
<div class='averagevis' style='display:none'>This div has to be shown/hidden for road team</div>
My guess is that something else is amiss. Inspect your page to ensure all elements are printed properly by your PHP. If everything seems fine, you could try using the jQuery "on" function, which should watch for new elements that match the selector. https://api.jquery.com/on/
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';
});
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);
I echo a button from a php script as following: print'<button id="testingbtn">TEsting</button>';
I use the id listen to the button and alert a notification message as following:
$('#testingbtn').click(function(){
alert('working');
});
The thing is that i used the same method before and it worked for me on all browsers but not anymore. can someone try to help me out the problem.
thanks guys..
Try this, we assuming your 'testingbtn' is dynamically added to the screen.
$(document).ready(function(){
$( "body" ).on( "click", "#testingbtn", function() {
alert('working');
});
});
I never recommend to do it in this way. Always put this code outside php.
HTML
<button id="testingbtn">TEsting</button>;
jQuery
$('#testingbtn').click(function(){
alert('working');
});
Also make sure jQuery is included in your code.
Point 1: Check whether you have included the jquery library or not.
Point 2: [If point 1 is OK], Where have you put your script? If you put your script before button code, than use document ready function
$(document).ready(function(){
$('#testingbtn').click(function(){
alert('working');
});
});
Alternately, if you want to put your code unchanged, than place your script after your button code[best practice: put them at the bottom of the page].
I don't use print. I always use echo to show it in my html page.
<?php
echo '<button id="testingbtn">TEsting</button>';
?>
In jquery:
$('#testingbtn').click(function(){
alert('working!');
});
Try reading this
I have this bit of code below which expands and collapses the results from a search. The search displays the search results on the same page so the whole page isn't reloaded. It works the first time - i.e the first search, however for future searches the expand collapse feature stops working. I think its because the page isn't reloaded but Im not sure how to fix it.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2 /jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.section').hide();
$('h2').click(function () {
$(this).toggleClass("open");
$(this).next().toggle();
}); //end toggle
}); //end ready
</script>
<?php include('db.php');
$descr = $_POST['search'];
echo '<ul id="user_list">';
$user_query = $db->query("SELECT * FROM tblVulns WHERE Name LIKE '%".$descr."%'");
while($user = $db->fetch_assoc($user_query))
{
echo ' <h2 style="cursor:pointer">'.stripslashes($user['Name']).'</h2>
<div class="section" style="display:none"> <h3>'.stripslashes($user['Risk']).'</h3><p>
<h4>'.stripslashes($user['Summary']).'<p>'
.stripslashes($user['Description']).'<p>'
.stripslashes($user['cveCode']).'<p></div>';
}
?>
The code at the bottom is the php receiving the search results. The code at the top is the js that is dealing with expand and collapse
Any help in how to get this work for all searches after the page has loaded would be great. Thanks
You are adding your event listener to the click event of any h2 elements that are present on page load. It sounds like you are then loading in new content and expecting the same code to work for them.
Instead, you will need to do this:
$("body").on("click","h2",function(){
$(this).toggleClass("open");
$(this).next().toggle();
});
Which will work on any h2 that is on the page. If you want only h2s in a certain container to have the effect then replace body for a reference to that element
EDIT:
I see now that you are using quite an old version of jQuery that doesn't support the on() function. I would suggest upgrading if you can, or use Abhishek Saha's answer if you cannot.
I think one of the reason, it doesnt work after the first search is because the new element which gets loaded, is not bind with the click action.
Try this:
replace
$('h2').click(function () {
$(this).toggleClass("open");
$(this).next().toggle();
});
with
$('h2').live('click',function () {
$(this).toggleClass("open");
$(this).next().toggle();
});