javascript jquery expand collapse search results - javascript

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();
});

Related

javascript wont find the id/class of html/javascript imported code with XMLHttpRequest

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!');
});
})

Click button on page load with div content changed

I have links which change content on click. I want one of the links to be cliked on page load and stay as active. Looks like it works in the below fiddle but when I add it on website this one is loaded :
http://jsfiddle.net/0e91svrr/
I think I have some mistake in JS:
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">//<![CDATA[
$(document).ready(function() {
$('a[class^=question]').click(function(e){
e.preventDefault();
var id = $(this).attr("class").replace("question","")
$('.new_member_box_display').html($('#answer' + id).html());
})
document.getElementById("modal").click();
});//end of ready
</script>
The code you have written is perfectly fine. I would just suggest try JQuery's trigger click.
$('#modal').trigger('click');
First of all don't used Pure JS with JQuery mixed up, it look so messy :D also I sugest you think about your tags class and ids :)
Try first add event to links and then call click in document ready like this.
$('a[class^=question]').click(function(e){
e.preventDefault();
var id = $(this).attr("class").replace("question","")
$('.new_member_box_display').html($('#answer' + id).html());
})
$(document).ready(function() {
$("#modal").click();
});

Toggle script inside a loop only works for first iteration

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/

jquery .load() function only working the first time

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();

.Show() not working in Jquery Mobile

I'm looking to simply hide and image before the page loads and then once the page has loaded to show the image. Problem is when I try to show the image it doesn't show the image at all.
Here is my html code:
<body>
<div id ="splash" data-role="page">
<center>
<div id='class'> <img src="BookBayText.png"></div>
<div id='book'> <img src="Book.png"></div>
</center>
</div>
</body>
Here is my javascript/jquery mobile:
<script type="text/javascript">
$(document).on('pagebeforeshow','#splash',
function()
{
$("#book").hide();
});
$(document).on('pageinit','#splash',
function(){
setTimeout(
function()
{
$("#class").animate({top: "1em"}, 'slow');
},3000);
//For some reason this line below doesn't run
$("#book").show();
});
</script>
Any ideas why this isn't working??
I managed to get the desired effect I wanted with the following code:
setTimeout(
function()
{
$("#class").animate({top: "1em"}, 'slow');
$("#book").show();
},2000);
Basically I moved the $("#book").show(); line into the setTimeout function. But it still leaves me a tad lost as to why the code wouldn't show the image outside the function. If anyone with the answer to this could update this answer it would really be appreciated.
kinda similar to this post jQuery mobile popup on pageinit .
Although the post blames a delay in the browser, for me it is still unclear why it does it. I have never experience such behaviour.
I wonder what if you do the following changes:
put your center tag inside a data-role:content,
replace pageinit for pageshow.
search your iem as follows
inside either pageinit or pageshow (not settimeout).
>
var elem = $("[data-role='page']:last").find('#book img'); // others may use $.mobile.activePage
if (elem.length) {
// check height or img width here...
}

Categories