Getting Data from button click for Jquery - javascript

I am using the "Second Solution" from this problem:
call the same jQuery function in multiple buttons
I am dynamically creating my buttons, based on an input, so there is currently 45 buttons! (used to select page number)
Is there a way to use the value of the button as data in my $.get so I can pull the data for the page?
$('.bclick').click(function(){
$.getJSON("url", { page: [need button data here] }, function(data){
//Some actionable code
})
});
.bclick is the class given to each of the buttons created.

when you are inside of the function, the reserved word this is a reference to your clicked button.
$('.bclick').click(function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
});
If your buttons are created dinamically probably this solution won't work. I may suggest you to use $.on():
$("parent selector or form selector").on("click", ".bclick", function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
})

If you are generating buttons dynamically, then use .on.
$(function(){
$(document).on("click", ".blick", function(){
var $this = $(this);
var buttonName = $this.attr("name");
});
});
Sample code

Yes you can by adding an extra attribute to your .bclick element, for example
<button class="bclick" data="your data here"></button>.
Then
$('.bclick').click(function(){
var buttonData = $(this).attr('data');
$.getJSON("url", { page: buttonData }, function(data){
//Some actionable code
})
});

Related

how to refresh only div with id=calender?

$(document).ready(function() {
$("#client-list").on("change", function() {
var selectedValue = $(this).val();
location.reload();
});
});
how to refresh only div with id='calender', instead of refreshing complete page, onchange dropdown list option? Complete source i have created a fiddle or how to keep slected option in drop down which was selected and refresh rest of the page?
You cannot reload only a part of your page unless you use IFRAMES.
Instead, you'll have to use AJAX. Here is a quick example:
<script>
function refreshCalendar()
{
$.ajax({
type: "GET",
url: 'http://yourdomain/api/whatever',
data: "", // You can send some data to the servers
success: function(data) {
$('#calendar').html(data);
}
});
}
</script>
You can refresh fullCalender as like this.
Put you calendar code in a function LoadCalendar then call it once on document ready and once on change of dropdown.
function LoadCalendar() {
$('#calendar').fullCalendar({
//your options
});
}
$(function(){
LoadCalendar();
$("#client-list").on("change", function() {
var selectedValue = $(this).val();
LoadCalendar();
});
});

jQuery .on not working after ajax delete and div refresh

On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.

jQuery Eventhandler for an dynamically added object

I got an problem with dynamically added DOM objects in jQuery. First of all I use this:
var $input = $('#search-input');
var $usersList = $('#ulist');
$input.on('input', function () {
$.ajax({
type: 'get',
url: '/userlist',
data: {query: $input.val()},
success: function (response) {
var json = JSON.parse(response);
$usersList.empty();
$.each(json, function (index, val) {
$usersList.append("<div id=\"listelem\">" + val + "</div>");
});
}
});
});
<div id="ulist"></div>
<input id="search-input" type="text">
to insert divs into usersList. This works well, but now I want to get val from this div when I click on it to process it further. I wrote this piece of code:
$usersList.on('click','#listelem', function(){
alert("clicked");
});
When I click on div I got proper alert, but now I have no idea how could I took data from inside of this element.
I don't know the proper engineering but I have dealt with similar issue while I was developing some requirements. basically as I understood you want to find out the target of the event and drag a value from there? if so you can do something like this:
jQuery(document).on('click', '#listelem', function(event){
var x = event.target.val();// event.target.value; depending on your situation and availability of the method.
});
Hope this helps.
try this
$(document).on('click','#listelem', function(event) {
alert($(event.target).text());
});
jsfiddle
Thanks you for help. for me proper option was to call
var mem =event.target.innerText;
you can do that with the regular javascript, you don't need Jquery.
document.addEventListener("click", function(e) {
if(e.target) {
console.log("item clicked ", e.target.textContent);
}
});
This should do the job to get the value of current target.

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Super simple JQuery Question - refresh static html

I have the following two functions that work great:
$(function(){
$('.trash_can a.delete').live('click', function(event) {
event.preventDefault();
var link = $(this);
$.post(link.attr('data-href'),
{
promo_id: link.attr('data-promo_id')
},
function(data) {
$('#page').html(data.html);
});
console.log('Clicked Delete');
});
});
$(function(){
$('#add-mod-form').bind('ajax:success', function(evt, data, status, xhr){
data = $.parseJSON(data);
// console.log(data.success);
if (data.success == true) {
$('#page').html(data.html);
$('#page box_bc').html()
}
else {
}
});
});
As data is received for page, I would also like to reload a static html element, $('#page box_bc') - How do I do this simple task with Jquery? Notice, i've tried it above, and that part does not work as planned.
Thanks
Use:
var $dataHtml=$(data.html);
$('#page box_bc').html($('#page box_bc',$dataHtml));
It is not very clear to me what you are trying to achieve. If the element is static what is the point trying to refresh it ? In case its content somehow depends on other elements of page : then it has to be reconstructed.
The code you have written fails because :
$('...').html()
returns the html content of that element. It does not do anything to the content. Probably it would be better if you could elaborate more on the context and purpose of the code.

Categories

Resources