Show modal on click using AJAX and JavaScript - javascript

Having an issue showing a modal window after I have parsed the JSON and placed the values into a TABLE TR.
$('#serviceload').change(function() // on dropdown select change
{
var page = $('#serviceload').val(); // dropdown selection set to page
if(page == "")
{
$('#completeProfile').hide(); // if page is blank, hide content
}
else
{
$.post('api/vesselSearch.php', {page: page}, function(data)
{
var obj = JSON.parse(data); // parse the data
$('#vesselinfo').empty(); // clear previous vessel content
var htmlToInsert = obj.map(function (item)
{
return '<tr><td>Edit</td><td>'+item.VESSEL_NAME+'</td></tr>';
});
$('#vesselinfo').html(htmlToInsert); // insert new vessel content
});
$('#completeProfile').show(); // show all content on page
}
});
As you will see above, after the JSON is parsed, I display the values in a TABLE row, which may have more than 1 row. The first TD cell contains a hyperlink which should open my edit modal.
The code to transfer the data from the row and display it in the modal looks like this:
$('#editVesselLink').click(function(e)
{
e.preventDefault();
$('#editVesselForm input').val(''); // clear previous values
$vessel= $(this).attr('data-vessel');
$('#editvesselname').val($vessel);
$('#editVesselInfoModal').modal('show'); // show the modal
});
Here is where my problem begins.
I am not sure where to place the code directly above. I have placed it inside the $.post beneath $('#vesselinfo').html(htmlToInsert);, and that was the only place I could get the modal to even open, but only for the first record.
Basically, I can only get the modal to open for the first record when I place the second piece of code inside the $.post . The modal will not open at all in any other place that I put the code.
I tried to use a $(document).ready(function{}); to no avail.
What am I missing?

Ok, I think that the problem is on:
...
return '<tr><td>Edit</td><td>'+item.VESSEL_NAME+'</td></tr>';
...
You can not repeat id property on the code, so, where is id="editVesselLink" put class="editVesselLink" and on $('#editVesselLink') put $('.editVesselLink')
why did it happens?
By HTML convection's the id have to be unique on HTML, so jQuery expects to recover only one element with that id, by default jQuery recover the first with that id if it is duplicated

Related

Adding a bootstrap attribute to cells in a DataTables.js column

I'm trying to add an attribute to the first column in my debatable so I just add a class in the columns[] setting called popperup.
However for the bootstrap popover to work I need to add the attribute "tabindex":"0"
This can be done with $(".popperup").attr({"tabindex":"0"})
however this only adds it to the first entries that load 10 in my datatable which then allows the popover to work the problem is when you click the next paginate button or numbered buttons it will not work as the tabindex:0 is missing
I have tried using
$("#Ttable3").on('page.dt', function() {
console.log("here")
$(".popperup").attr({"tabindex":"0"})
});
This only works once you have gone to the next page and then go back again. so you click next page or go to page 2/3/4 etc nothing happens. you go back to page 1 then back to page 2/3/4 and it will work
how can I get it so "tabindex":"0" is on every cell in a column
spend hours working on an issue and fix it the moment you post it on Stackoverflow
I needed to use draw.dt in the on call.
so this
$("#Ttable3").on('page.dt', function() {
console.log("here")
$(".popperup").attr({"tabindex":"0"})
});
becomes this
$("#Ttable3").on('draw.dt', function() {
console.log("here")
$(".popperup").attr({"tabindex":"0"})
});
Assuming you have defined your DataTable and assigned it to a variable...
var table = $('#example').DataTable( {
// your options here
} );
Then you can use the following to iterate over every node in the first column, using the table reference you defined:
var selectedCol = table.column(0).nodes();
for (var i = 0; i < selectedCol.length; i++) {
$(selectedCol).attr({ "tabindex": "0" })
}

Dynamically loaded JS needs to be clickable just like it's in the html

My page fires off an ajax query, where the MySQL Db is queried and the results are returned. (all successful).
Those results are formatted for output as a shopping gallery/catalogue and also as an accordion filter menu. So I can filter the shopping catalogue display. eg say I want to see only items that are red.
All is working so far.
My problem is with the filter accordion menu - dynamically created in js.
When I click on any selectable item in the tab-content, nothing happens. This means the parameter that should be sent, isn't being sent.
If I hard code the accordion filter or even load it with my server-side language, into the html directly, the filtering does send off the parameter and so the shopping catalogue is adjusted accordingly but, in that scenario, I am unable to dynamically change the filter menu.
I think the code I shall post below is the relevant code that recognises changes in the originally loaded content and fires off the ajax but (I think) it doesn't understand any changes to textboxes in the dynamically loaded content.
Please help me to understand what I need to add that will make dynamically loaded content fire-off to the ajax calls.
var $checkboxes = $("input:checkbox");
function update_nav_filter(opts) {
$.ajax({
type: "POST",
url: "/php-queries/product-filter-query.php",
dataType: 'json',
cache: false,
data: {
filterOpts: opts
},
success: function(records) {
//console.log(records);
//alert('SUCCESS!');
// alert(records);
$('#filters_div').html(makeFilter(records));
}
});
}
$checkboxes.on("change", function() {
//alert('there is a change is checkbox status'); // working on page load but not when any checkbox is clicked-on
var opts = getCatalogueFilterOptions();
updateCatalogue(opts);
update_nav_filter(opts);
});
$checkboxes.trigger("change");
Any help greatly appreciated.
I have created an event listener.
Following page-load, I select an item in the JS generated nav filter. eg pedal_bins in the sub_category section. I am then shown a display of pedal_bins. :)
Then I select 'kettles', another sub_category but I can only see the last sub_category that I click on. The pedal_bins disappear.
How best can I build and remove items with a single click? Store in a session parameter and then
a. remove the latest click if it matches whats in the session
b. add the latest click if its not already in the session
Then submit whatever the array is at that stage?
Or, is there a better way to run this?
Here's the listeneer
enter code here
document.getElementById("filtering_div").addEventListener("click",function(e) {
// e.target was the clicked element
if (e.target && e.target.matches("input")) {
var parameter = e.target.id;
//console.log("Anchor element", parameter , " was clicked" );
var opts = getCatalogueFilterOptions(parameter);
console.log(opts);
// update_nav_filter(opts);
updateCatalogue(opts);
}
});
You have a "delegation" problem. When you create a dynamic element, in order to be able to act on the newly created element, you have to reference it as a child element that was originally loaded with the DOM.
For example, if you have an element called <div id="top"></div> and you create a dynamic element, let's say <button id="test">Click</button> in there, you'll have to refer to that div when adding an event listener.
$("#top").on('click', '#test', function(){
//event related code goes here.
});
Here is a fiddle I created that explains the whole thing with some examples.
If you have any questions about it, please let me know.

Get index of td elements in table using Javascript or jQuery

So I have a table.. It's in jade templating format so i've not created a jsfiddle for it.
Anyhow, the user clicks a button within the table and this toggles a class which displays all the information to do with that table.
The user clicks and this code gets executed:
$(function() {
$('.information-button').click(function() {
detailsPopup(this);
});
});
The onclick calls the function below:
function detailsPopup(el) {
// $(el).find("td").each(function(index){
// var bookingData = $(this).html();
// })
array1.indexOf(td [ fromIndex])
console.log($(el));
$(".details--info, .overlay--contain").toggle('600');
}
The problem i'm having, is I need to loop through all the td elements of the booking, grab the index and pass it through the onclick event. So when I toggle the class that displays the information, it only shows the information for that table cell.
Anyone know how I can achieve this? Thanks!
use Index in jquery.
select parent and get index number.
i.e:
$(el).closest('tr').index();

edit a textarea in jquery popup box

I have a div in which contents are displayed in ordered list with a checkbox for each. these are displayed by fetching from the database. now i need to display the content near to the selected check box. what i did so far is
1) only one check box can be selected at a time
2) get the id of the check box which is selected stored to variable ids
3) then paragraph content id = "p"+checkbox id
The code is:
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
});
});
function edit_temp(prt){
var checkedAtLeastOne = false;
$('input[name="check_clinic"]').each(function() {
if ($(this).is(":checked")) {
checkedAtLeastOne = true;
ids = $(this).attr('id');
}
});
if(checkedAtLeastOne){
p_id ="p"+ids;
alert(p_id);
}
else{
alert('Please select any clinical Interpretation');
}
}
So far this is working perfectly. but now i need to display the content of the <p> tag with id p_id in a text area inside a popup window. and then edit the text and by clicking the update button of popup box that content must be updated in db.
can anyone help me to find a solution for this.
You need to create a php file that will receive the row id from database and prints it to textarea in a form. and when user clicks submit the form action will update the db. Here are the step by step guide what you need to do:
Add an "a" tag which opens popup.php?id=1 (where 1 is the id of the row)
Create the popup.php file, which fetch record from database
Add a form element with textarea and submit button in popup.php and populate your textarea with the value fetched in step 2
Either create a new file called update.php or check if the page has post request in popup php and update the value in db with the given id and textarea value.
Hope this will help you to finish.

why data method not working properly while getting ID?

I am trying to get Id using data method of jquery.I saw One example which is working fine.
http://jsfiddle.net/4ajeB/6/
In this example when user click add button generate dynamic rows.there is icon on right side ":" it open pop up .on click edit it give the id of row.Actually In this example developer use this
$('.edit_h').data('originalId', id);
Same thing when I used in my example it gives last value.In other words if you generate three row and click any icon of row it show "tc_3" only.I also used same concept .But I don't know why my output come wrong.
http://jsfiddle.net/4ajeB/7/
$('.edit_h').click(function(){
alert("edit ID:"+$(this).data('originalId'));
})
The problem is that your are calling:
$('.edit_h').data('originalId', id);
every time you add a test case. As you only have one popup menu, you are replacing the data attribute on the menu each time, so the last one added will always be there.
The data attribute should be on the listitem not the popup, then when you click the listitem, retrieve the id and write it into the menu data attribute.
$(document).on("click", ".edit_delete_copyFunctiontiy_h", function (e) {
var id=$(this).data('originalid');
$('.edit_h').data('originalid', id);
$("#Mainnavpanel").popup("open", {
positionTo: $(this)
});
});
$('.edit_h').click(function(){
alert("edit ID: "+ $('.edit_h').data('originalid'));
})
Updated FIDDLE

Categories