Jquery: bind several dynamically added elements to an html() event - javascript

I have in my page several dropdowns that will be dynamically updated using AJAX, in this way:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response);
}
The dropdowns have names in this format:
<select id="elemento_1" class="dropdowns">
<select id="elemento_2" class="dropdowns">
<select id="elemento_3" class="dropdowns">
The PHP responds with a string response in the form <option value=1>Bla<option value=45>Ble … and it gets appended to the dropdown. You get the idea.
Initially there's only one dropdown, but whenever the user clicks a button, a new dropdown will be added and loaded using the method above, and I want it to have by default the same value than the previous dropdown. After reading this answer about how to trigger html() events:
https://stackoverflow.com/a/3616565/470994
I changed the code above to the following:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response).triggerHandler("cambia");
}
$(".dropdowns").unbind().bind("cambia", function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
alert("Mooooo " + numero);
if (numero > 1) {
var anterior = $("#elemento_" + (numero - 1)).val();
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
}
});
Which inspects the dropdown in question and, if it's not the first one, will get the value of the previous dropdown and load it in the current one.
Now, this is all fine and well… except that, in my tests, the event only gets triggered when the first dropdown is loaded (the alert("Moooo") only appears in the first dropdown). If I press the button, the 2nd, 3rd… dropdowns appear, but the event isn't triggered. I suspect that it's because of the explanation here:
https://stackoverflow.com/a/6173263/470994
(bind only works for the elements that exist initially, not the ones added later).
The suggested solution is to use on()… but I don't know exactly how to use it to capture custom events like the one I've defined for html() changes. Can you even do that? Is there any other solution?
Thanks.

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

Make click-event on "responsive" dropdown item in javascript

I have a maven-project and get the users via a spark get-call from a database:
function allUsers(){
$.ajax({
dataType: 'json', //to parse string into JSON object
type: 'GET',
url: 'webAthen/api/users',
success: function (data){
$('.userDropdown').html("");
for(i=0; i < data.length; i++){
$('.userDropdown').append("<option>" + data[i].userName + "</option>");
}
}
});
}
Know if I click on such a user in the Dropbox, I want the information of this user right in labels like:
$('.userDropdown').val().click(function(){
alert($('.userDropdown').val() + " was clicked :-)");
});
I inserted the alert to get an alert with the username that was clicked, but it doesn't work at all. If you need further code, just let me know! I already googled and found some examples with firm values. But my dropdown-entries are kind of dynamically from the database.
After looking at your code, I feel like, the option tags are created dynamically. So the newly created options/elements are not bound by Click listener.
$(document).on("click", ".userDropdown > option", function(){
// Your code...
});
The above code will Listen to the onClick event of document first, and later it's narrowed down to the targeted element.

Dynamically altering the template for a Bootstrap popover

I've checked out this question which was asked about dynamically changing Bootstrap popover content. But the solution doesn't seem to be working out for my case where I want to show fresh data to the user every time they press the button to reveal my popover by changing the data-template directly.
here's my .js code:
$(function () {
myUrl = "" + window.location.protocol + "//" + window.location.host + "/" + "Demo/Notification/LoadingStats";
$.ajax({
url: myUrl,
type: 'GET',
success: function (data) {
$('[data-toggle="popover"]').popover({
template: data
});
}
})
The above code is the working code I have at this moment which displays the data I want correctly, but does not change fluidly or when the user opens it. Only when the page is reloaded does the data update.
The below code is my non-functioning attempt at changing the data-template based on the reference I linked above. It seems to be firing, according to the alerts and debuggers I've thrown inside, but doesn't seem to do anything (it doesn't even display the popover once)
I've even tried using setInterval(myfunction, 2000);
$('[data-toggle="popover"]').on('show.bs.popover', function () {
$.ajax({
url: myUrl,
type: 'GET',
success: function (data) {
$('[data-toggle="popover"]').popover({
template: data
});
}
})
});
//these following three lines are firing correctly, just not doing what I want (refreshing the popover)
var popover = $('[data-toggle="popover"]').data('bs.popover');
popover.setContent();
popover.$tip.addClass(popover.options.placement);
})
});
Any ideas on what I might be doing wrong,
or how to go about Dynamically changing the data-template of a popover?
UPDATE
I've been overlooking the data-html="true" attribute which is why I've been thinking I had to use the data-template instead of data-content. You can NOT dynamically update the data-template, but you totally can dynamically update the data-content. I hope this helped someone out there who overlooked the data-html.
I've been overlooking the data-html="true" attribute which is why I've been thinking I had to use the data-template instead of data-content. You can NOT dynamically update the data-template, but you totally can dynamically update the data-content. I hope this helped someone out there who overlooked the data-html.

Make ajax request and success data show in id <select></select> part

See this link..
My HTML page contains a similar multiple select drop down. Something like this -
<select id="box" data-placeholder="Choose from available option.." class="chosen-select student-select" name="classes" multiple style="width:310px;" tabindex="4">
</select>
In this select drop down, I'm trying to print <option></option> by making an Ajax request and showing the success data there.
When I used a simple <select></select> without using the chosen style, I can see the options there. But when I use the chosen style near the select (multiple selection) then is doesn't shows the options.
document.getElementById("box").innerHTML = data;
I am doing something like this.Please, help why it doesn't show me when I used that chosen effect.?
$(document).ready(function(){
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: '../folder/page1.php',
data: "mid="+Id,
success: function( data ) {
alert(data);
document.getElementById("box").innerHTML = data;
}
});
});
});
You will need to initiate chosen after the new html has been loaded in the page via ajax.
This has been answered in this question.
Chosen not working on elements from AJAX call
You only can show the HTML output in DOM. I am assuming that you're getting options after ajax request. Just try to change like
$(document).ready(function(){
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: '../folder/page1.php',
data: "mid="+Id,
success: function( data ) {
$("#box").html(data);
$(".chosen-select").chosen();
}
});
});
});
After AJAX call you should initialize your select box. try and share the results.

AJAX dropdown within toggle(function) only works once

I have a table where rows are dynamically added.
In one of the cells I would like to toggle between a dropdown and an input box.
The dropdown is a PHP file loaded via AJAX. The issue is the dropdown only renders once.
First time you click the toggle button, the dropdown appears, as it should.
Second click switches it to the input field, as it should.
Third click does nothing, it just stays on the input box and does not toggle back to the dropdown.
If I comment out the AJAX call and put in a simple dropdown, it toggles back and forth just fine. So I believe the issue is with the AJAX portion.
Link to http://jsfiddle.net/6h5BD/1/
NOTE: the AJAX is currently commented out in jsfiddle and replaced with a temp dropdown so you can see what results I am looking for.
The portion of JS in question:
$('input[name="button"]').toggle(function() {
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$('#brand').html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
The PHP:
$sqlbrand = "SELECT BRD_Name FROM Brands ORDER BY BRD_Name asc";
$resultbrand = odbc_exec($conn, $sqlbrand);
ECHO "<select name='itemBrand[]' style='width:120px' size='1'>";
while ($rowbrand = odbc_fetch_array($resultbrand)) {
echo "<option value='".$rowbrand['BRD_Name']."'>".$rowbrand['BRD_Name']."</option>";
}
echo "</select></td>";
I am very open to handling this in a different manner. I have tried several different approaches, but to no avail.
Thank you in advanced for any assistance with this issue.
I cant completely help you debug if I can't see the PHP file.
But from the HTML/JS I can see a potential problem. You are selecting $("#brand") and changing the html to the output_string. But when you are cloning your rows, you are making multiple divs with id of #brand and ids are supposed to be unique, you should use class instead.
Can you try if this works?
$('input[name="button"]').toggle(function() {
var $this = $(this);
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$this.closest('td').prev().html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
In your code (in the fiddle)
$(this).closest('td').prev().html(...)
should be
$(this).closest('td').prev().find('#brand').html(...)
because $(this).closest('td').prev().html(...) is replacing the html of td which means it's just removing the div with id #brand from within the td so in your ajax success callback $('#brand').html(output_string); is not working because it's not inside the td once you toggled it.

Categories

Resources