I have a few different modals on my page that need data passed into them. I solved that problem with this other question, which has me using jQuery now and was really helpful. This is what I have now:
$(document).on("click", ".edit", function () {
$(".modal-body #value").val($('.edit').data('id'));
});
My problem is that since my page has dynamically created buttons (from a foreach based on the model), no matter which button I click, this gets the value from the first button. How do I instead get the value from the button that was clicked.
I thought about giving them all separate ids, but I don't want to make a function for each id. I read that there is a data property to this .on method, but I can't find a good example of how to use it and if it would work in my case.
If anyone has any suggestions I would be very grateful. Thank you!
$(document).on("click", ".edit", function () {
// Use $(this) to reference the clicked button
$(".modal-body #value").val($(this).data('id'));
});
You can reference the button being clicked by using the this keyword. Try the following:
$(document).on("click", ".edit", function () {
$(".modal-body #value").val($(this).data('id'));
});
Use Bootstrap's events:
$('#your-modal').on('show.bs.modal', function (e) {
var btn = $(e.relatedTarget);
var id = btn.data('id');
$("#value").val(id);
});
See the "Events" section of http://getbootstrap.com/javascript/#modals :
[The show.bs.modal event] fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.
Related
I would like to set a value via a form in a modal and have that value reflected on a disabled textbox in the main screen. What are the best options out there?
It can make work using jQuery with the help of event handler
Handle click event of modal dialog, pass data by selecting #Id into modal and show it
Something like.,
$(document).on("click", ".open-modalDialog", function () {
var mytxtInput1Id = $(this).data('txtInput1');
$(".modal-body #txtInput1").val( mytxtInput1Id );
//you have call modal to open here
$('#addModalDialog').modal('show');
});
Assuming this is bootstrap5:
It seems like you should only get the value after the modal closes... which is what the function attached to myModalEl.addEventListener does.
event.target typical returns the element that has the event listener attached to it, but like I said in the comments in the code below, if it doesn't, then there are a million and one different ways to do so.
var myModalEl = document.getElementById('myModal');
myModalEl.addEventListener('hide.bs.modal', function (event) {
// getElementsByName returns a list of elements, so be sure to select an element to perform on
document.getElementsByName("name_of_hidden_element")[0].value = event.target.getElementsByName("name_of_element_inside_of_modal")[0].value
//event.target.... should work to get the element from inside the modal, but if it doesn't there are several other ways to do so.
});
I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};
After clicking on the icon with ids (#prevleft and #nextright) , an ajax function is called. During the time ajax function loads a new table, I want to disable the icon click.
HTML Code:
hrHTML='<tr><th colspan="5"><i class="icon icon-chevron-left icon-2x lr"
style="float:left;" title="Previous Five Weeks"
id="prevleft"></i>' +"Weekly Utilization"+'<i class="icon icon-chevron-right
icon-2x lr" style="float:right;" title="Next Five Weeks" id="nextright"
></i></th>
</tr>';
The table row is appended dynamically as shown above. Want to disable #prevleft and #nextright after one click.
The following line doesn't work:
$('#prevleft').prop("disabled", true);
I am new to coding, so all help is appreciated.
Just check with the version of the jquery your using, I hope that your using jquery 1.5 or below
For jQuery 1.6+
Use can use .prop() function:
$('#prevleft').prop("disabled", true);
$("#nextright").prop("disabled", true);
For jQuery 1.5 and below
You need to use .attr() and disable the icon
$("#prevleft").attr('disabled','disabled');
$("#nextright").attr('disabled','disabled');
and for re enable the icon (remove attribute entirely):
$("#nextright").removeAttr('disabled');
$("#prevleft").removeAttr('disabled');
Assuming you have an event handler on a icon, in any version of jQuery you can use the following property to check if your icon is enabled or not
if (this.disabled){
// your logic here
}
Bind simple a click event when clicked on prevleft and prevright id icon.
$("body").on("click","#prevleft ,#prevright",function(){
var _this = $(this);
$(this).prop("disabled","true");
// ajax call code right here
// on ajax success function right this line
success: function(resp){
_this.prop("disabled","false");
}});
})
You have attached an event listener to one or more elements that do not yet exist in document. You can use event delegation, or jQuery() function to attach event to element when created.
Pass html string to jQuery(), use .find() to get "#prevleft", #nextright selectors, attach click event using .one(), append jQuery() object to document
$(elementWherehrHTMLIsAppended)
.append(
$(hrHTML)
.find("#prevleft, #nextright")
.one("click", function() {
$(this).prop("disabled", true)
}).end()
);
You can add a class to the element and check for the class when the user clicks.
For example:
$('#prevleft').click(function(){
if($(this).hasClass('clicked')){
// do nothing or return false
}else{
// ajax call
// on a successful call you can add the class using:
$('#prevleft').addClass('clicked');
}
});
Let me know if this is what you were asking for. This also gives you the ability to add an alert or do something if the button was already clicked.
Hope this helped!
Try my code, this event only called when icon hasn't class 'clicked', in the first call we will add 'clicked' class to prevent this event from this time.
$('#prevleft:not(.clicked), #nextright:not(.clicked)').on('click', function(){
$(this).addClass('clicked');
});
Hope this can help you!
I went through many post from SO but not able to relate with my scenario.
I have this code on button click. by which User can create as many div on runtime as he wants to on UI.
$('#adddiv').click(function () {
debugger;
$('#main').append('<div class="ara-dynamic-div">
<div class="box box-solid bg-light-blue-gradient">
</Div></div>');
});
code to get buttonclick event from that div
$(document).on('click', '#remove', function () {
showMakeAndHold(this);
});
function showMakeAndHold(obj) {
alert(obj);
$('.ara-dynamic-div').fadeOut();
}
Now the problem is that I have to create multiple dynamic div. and each div will have button to close itself. When I call this function it will close all created div's instead of the one which button is clicked.
I am not able to find the proper div by which request for close come. I am new to DOM and JQuery. not able to relate the things
First of all, if you're using multiple divs you shouldn't give the close button an ID, but a class instead (let's say, .close)
Next you can use event delegation to find the correct element:
$(document).on('click', '.ara-dynamic-div .close', function( event ) {
$(this).closest('.ara-dynamic-div').fadeOut();
} )
The delegator handles all click events in any .ara-dynamic-div .close button, catching them all and allowing you to use $(this).closest(...) to get to the parent container.
Edit: Corrected a mistake
You can use jQuery's .closest() function.
function showMakeAndHold(obj) {
alert(obj);
$(obj).closest('.ara-dynamic-div').fadeOut();
}
JSFiddle
Replace this:
$(document).on('click', '#remove', function () {
showMakeAndHold(this);
});
by this:
$(document).on('click', '#remove', function () {
$(".ara-dynamic-div").not($(this).parents(".ara-dynamic-div")).fadeOut(function () {
$(this).remove();
});
});
Here is the JSFiddle demo
What the code does is that it remove all other .ara-dynamic-div except the one for which the button was clicked.
Take the following code,
// Update button clicked
function updateEntity(e) {
e.preventDefault();
var name = $(this).attr("name");
...
// some stuff
...
}
$(document).on("click", ".updateEntity", updateEntity);
Currently I have this for (go figure) updating an entity I've editted on button click. Now, its parameter is particularly expecting a jQuery event. However, I want to also be able to call this function (end goal: to minimize code) outside of a jQuery event. Like so,
// Do an update but then redirect to prevent adding the same estimate twice.
function createEstimate(e) {
updateEntity(e);
var link = $(this).attr("href");
window.location.href = link;
}
$(document).on("click", ".createEntity", createEstimate);
Question: How would I go about calling updateEntity or setting the function up, so that I can supply it to the click-event handler and call it like a function and still have it used correctly? Is this goal realistic or should I be structuring this differently if I want to achieve such a goal?
(Encase it is not obvious, my current problem is that on the function call updateEntity(e); $(this) becomes window instead of the clicked link.)
Use .call to set this correctly:
updateEntity.call(this, e);
Learn more about this.