Make click-event on "responsive" dropdown item in javascript - 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.

Related

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.

Passing loop data as variable from JavaScript to AJAX via Bootstrap modal

My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click
should alert users_id in a Bootstrap Modal popup.
The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.
Below is the code for retrieving records in JavaScript along with Bootstrap modal button:
<script>
$(document).ready(function () {
$.post('users.php', function(response){
$.each(JSON.parse(response).items, function(i,v) {
$('.userslist').append('<span>'+v.id+'</span> Profile');
});
});
});
</script>
Below is the code for posting the users_id and then alert it:
<script>
$(document).ready(function(){
$(".modalLink").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(data) {
$("#rmm").html(data);
}
});
});
});
</script>
but if I take the Modal button outside the retrieve records in a javascript loop
it will alert users_id and everything will work fine as in code below
Profile
Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.
Thanks
If I understand your question properly;
Try changing
$(".modalLink").click(function() {
to
$(document).on('click', '.modalLink', function() {
Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.
If you get the expected result, I would drop the document selector and use the closest parent static element.

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

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.

Having issues calling an ID after I have appended data from an ajax call

Ok,
So I have a .on click event which is called to an ajaxed script. The script returns a set of HTML information.
Now, what I seem to be having an issue with and maybe I am just not typing the right search terms in for this so my apologies if this was answered already.
When the html is appended to the correct box, the user is then able to click a link on that box, drop down the box and see a new input box. The user should be able to type the text in and hit the enter key and it should work.
When I run an inspect element, I do see the element's ID properly inserted, but it is like javascript doesn't even recognize the new element id.
UPDATE: I am really not sure why you need code to be able to answer this question, however here it is. The code works normally unless the above happens so yes I am appending it, and yes I am SURE i am appending it, please make sure to read everything before posting a comment, thanks!
$('body').on('keypress', '.peapComment', function(event) {
if(event.which == 13) {
var peap_id = $(this).attr('rel');
var comment = $(this).val();
$.ajax({
type: "POST",
url: "index.php",
data: {
page: "postPeapComment",
peap_id: peap_id,
comment: comment,
}
}).done(function(msg) {
console.log(msg);
$('#comment_' + peap_id).append(msg);
});
console.log('Send to Peap #' + peap_id + ': ' + comment);
$('#commentbox_' + peap_id).val('');
}
});
I have tested your code, and it seems to work without problems for me. My assumption would be that the data returned from your ajax call, is failing to return the proper "Peap_ID" or not returning anything all around, as this is the only way I can reproduce what you have claimed your error is, otherwise the code you have posted looks great.

onClick Modal Dialog

Similar to: jquery modal dialog onclick?
However I have a different requirement and cannot apply the solutions provided in that post.
At the moment I am using JQuery within php to parse through an xml file and produce content on a HTML page:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "uploads/data.xml",
dataType: "xml",
error: function() {
$('#message').text('Please upload the XML file.');
},
success: xmlParser
});
});
function xmlParser(xml){
$('.tmpli').hide();
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
});
}
</script>
I attempted an alert triggered by onClick however it's not able to contain images:
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet" onClick="alert(\''+$(this).find("name").text()+'\');">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
});
I then attempted this however it opens a dialog box for every li element on the page and I'm unsure how to edit the text and add an image:
$(xml).find("vendor-one").each(function(){
$("#vendor-one").append('<li class="sweet">' + $(this).find("name").text() + '</li>');
$(".sweet").fadeIn();
$('li.sweet').click(function(){ $('li.sweet').dialog(); });
});
I need a facility where I am able to click on each individual li item created and have a message box appear that contains an image and text.
I was intending to use this: Modal Dialog however I'm unsure of how to mend it to my needs.
How do you do this?
Instead of using the manual onclick inline option, you can use the Javascript way to do it.
document.getElementById('ElementID').addEventListener('click', function(event){
console.log(event);
});
Or the JQuery way (which results in the same thing) :
$('#ElementID').click(function(event){
console.log(event);
});

Categories

Resources