Setting jQuery value into c:foreach loop - javascript

I am basically trying to get values with an ajax request based on a specific id. I then would like to load the json List returned, and load it into a jstl foreach loop. This is my code for the ajax GET request:
$(this).on("click", ".edit_sighting", function(){
var username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings) {
});
});
My Button that gets pressed to load these values: So when this is instantiated, I want to load all the sightings that user has into a modal.
<button class="edit_sighting" value="${sighting.username}">Edit Sighting</button>
I want the returned 'sightings' to go into a c:foreach loop to show if the user has more than 1 sighting.
<c:forEach var="" items="${?}">
</c:forEach>
I dont know how to set the jQuery value returned into the 'var' section?
Thanks

Try this:
$(this).on('click', '.edit_sighting', function() {
$.get('${pageContext.request.contextPath}/getSighting/' + $('.edit_sighting').val(), function(sightings) {
$('c\\:forEach').attr('var', sightings);
});
});
Also, why are you using $(this) as a selector when binding the click event?

Related

div element hides when load() function is called

I'm working on making ordering by some criterias(e.g. by price, by author) on my jsp page. And using ajax to reload content of div when new sorting option is selected. But when reload function is called, it just hides div on web page. I've checked out, that there are books in session scope needed to be shown and Jquery is included correctly. This is html for choosing criterias to sort by:
<select>
<option id="default">Default</option>
<option id="price">By price</option>
<option id="author">By author</option>
</select>
And here is a code for processing click events for select element:
$(document).ready(function () {
$('select').change(function () {
$( "select option:selected" ).each(function() {
let sortAttr = $('option:selected').attr('id');
$.ajax({
// passing data to servlet
url: 'http://localhost:8080/sort',
type: 'GET',
// sort criteria
data: ({sort: sortAttr}),
// div needed to be reloaded
success: function () {
$('#mydiv').load(' #mydiv');
}
});
})
});
})
And code on jsp page for the div needed to be reloaded:
<div id="mydiv">
<c:forEach var="book" items="${sessionScope.books}">
<div class="col-4"><a href="/home?command=book_details&isbn=${book.ISBN}">
<img src="data:image/jpg;base64,${book.base64Image}">
<h4>${book.title}</h4>
<p>${book.price}$</p>
</a></div>
</c:forEach>
</div>
Any ideas why this happens?
EDIT
Finally, I found out what's happenning. The important thing to notice(especially for me) in .load() function is that whenever we call this function, it actually not just refreshes div content with new data, but makes request to the provided url and on that page(which url we provided) looks for the div selector, gets it's content and then goes back and inserts that content in current div. Notice, that If we don't write url, .load() function will make request to current page (correct me please, If I'm mistaken).
Hope that will help somebody!
First of all, you need to fix the typo in your code. Having space at the beginning of JQuery identifier won't find the required element.
Change this: $('#mydiv').load(' #mydiv');
To this: $('#mydiv').load('#mydiv');
Also, I think you're using it the wrong way.
Check the documentation here
How about
$(function() { // on page load
$('select').on("change", function() { // when the select changes
let sortAttr = $('option:selected', this).map(function() {
return $(this).attr('id')
}).get(); // get an array of selected IDs
if (sortArrr.length > 0) {
$('#mydiv').load('http://localhost:8080/sort?sort=' +
sortAttr.join(',') + // make a comma delimited string
' #mydiv'); // copy myDiv from the result
}
});
})

CasperJS click is leads to error even when the element exists

I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);

Select2 on elements loaded with JQuery

I'm using select2 on a project, and is working as it should, initiating the select2 using:
$(function() {
$(".elegible").select2();
});
The issue comes in when I'm trying to call de function to elements loaded by JQuery, I don't know how to call that function. I've tried "on" but it does not load the selects with the select2. The only thing I found is this:
$(document).ajaxComplete(function(e, xhr, settings){
$(".elegible").select2();
});
But this calls that function every time an ajax call is completed, even in those cases when I'm not needing the select2. My question is: How can I call the select to on elements loaded later? Is the method that I'm using right now valid? Can I improve that?
Thanks!
Adding Info:
I call the new content by getting it from another page - which loads the select - using ajax:
$.get('detalle_miembro/' + this.id)
.done(function(result) {
$('#detalle_miembro').html(result);
});
And placing it, in a div: <div id="detalle_miembro"></div>
Here is how you can call select on just the new content added:
$.get('detalle_miembro/' + this.id).done(function(result) {
$('#detalle_miembro').html(result).find(".elegible").select2();
});

how to tell the program the value of an element is refreshed

How can refresh an html element when its value is changing. I mean assume that i have this tag:
<div id="response" style="display:none;"><div>
and i have this script:
<script type="text/javascript">
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').html('').load('{% url messages_delete message.id %})
alert($('#result').html());
$('#'+$('#result').html()+'_list').trigger('click');
});
</script>
when user clicks on delete_link, the server sends a value to response div, so response div which was empty before, now has a value, and i will use it's value to know which tab i should trigger. when i use alert, it understands that the value of this tag is changed, and the trigger works. but without alert, it seems it doesn't understand the value is changed and trigger doesn't work. Is there a way to tell the program that the value is changed? i don't want to use alert. thanks very much for your help
.Load() is asynchronous, you need to set your content html in the load callback function.
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').html('').load('{% url messages_delete message.id %}',function(){
$('#'+$('#result').html()+'_list').trigger('click');
});
});
AJAX is asynchronous, you can use the load callback function which is executed after request is complete.
$('#delete_link').click(function(e) {
e.preventDefault();
$('#result').load('url', function(){
$('#'+ $(this).html() +'_list').click()
})
});
Note that load before adding new markup, removes the current markup of the element, so using html('') is redundant.

Load Html Content if not exist JQuery AJAX

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

Categories

Resources