how to upload a file using ajax jquery with showing progress bar while uploading in struts2 i searched every where no luck can any one give me idea or some code snipplet thank you.for now i am using normal upload in html like this.
<a id="addFile-link" href="#" title="add file"><img src="htdocs/images/add_file.png" style="width: 20px; height: 20px; border: 0"></a>
<form id="form" name="form" target="viewFileUpload" method="post"
action="fileUpload.do" enctype="multipart/form-data">
<input type="file" name="upload" id="file" class="fileUpload" multiple>
</form>
$("#addFile-link").click(function() {
var initialFolderId = document.getElementById('currentFolder').value;
//Added for converting first time page load null or empty value validation in Servelet engine
if (initialFolderId == null || initialFolderId == "") {
initialFolderId = 0;
}
document.getElementById('selectedFolder').value = initialFolderId;
$("#file").click();
var uploadElement = document.getElementById("file");
$('#file').change(function() {
uploadElement.form.submit();
//sleep(100)
setTimeout(function() {openFolder(document.getElementById('currentFolder').value);getRecentActivity(0);}, 3000);
$('#Activites').html("");
});
});
$('#addFile-link').bind("click",function(){
var FolderId
FolderId=document.getElementById('currentFolder').value;
document.getElementById('selectedFolder').value = FolderId;
if( FolderId==" " || FolderId==0){
$('#input').prop('disabled', true);
showFileMSg();
//alert("kindly select a folder to upload files");
}
else{
$('#input').prop('disabled', false);
$('#fileupload').fileupload({
xhrFields: {withCredentials: true},
url: "fileUpload.do?",
type:"POST",
dataType : "JSON",
autoUpload: true,
formdata:{name:'FolderId',value:FolderId},
disableImagePreview:true,
filesContainer: $('table.files'),
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-upload fade">' +
'<td><span class="preview"></span></td>' +
'<td><p class="name"></p>' +
'<div class="error"></div>' +
'</td>' +
'<td><p class="size"></p>' +
'<div class="progress"></div>' +
'</td>' +
'<td>' +
(!index && !o.options.autoUpload ?
'<button class="start" disabled>Start</button>' : '') +
(!index ? '<button class="cancel">Cancel</button>' : '') +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-download fade">' +
'<td><span class="preview"></span></td>' +
'<td><p class="name"></p>' +
(file.error ? '<div class="error"></div>' : '') +
'</td>' +
'<td><span class="size"></span></td>' +
'<td><button class="delete">Delete</button></td>' +
'</tr>');
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.name').text(file.name);
row.find('.error').text(file.error);
} else {
row.find('.name').append($('<a></a>').text(file.name));
if (file.thumbnailUrl) {
row.find('.preview').append(
$('<a></a>').append(
$('<img>').prop('src', file.thumbnailUrl)
)
);
}
row.find('a')
.attr('data-gallery', '')
.prop('href', file.url);
row.find('button.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
},
always:function (e, data) {
$.each( function () {
$(this).removeClass('fileupload-processing');
});
},
done: function (e, data) {
$('.template-upload').remove();
$.each(data.files, function (index, file) {
openFolder(FolderId);
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
/*add: function (e, data) {
$('body').append('<p class="upl">Uploading...</p>')
data.submit();
},*/
})
}
});
<form id="fileupload" on action="fileUpload.do" method="POST" enctype="multipart/form-data">
<input id="input" type="file" name="upload" multiple style="cursor: pointer; display: none">
<im:hidden name="selectedFolder" id="selectedFolder" value="1" />
<span class="fileupload-process"></span>
<div class="col-lg-5 fileupload-progress fade">
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-info" style="width:0%;"></div>
</div>
<div class="progress-extended"> </div>
</div>
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
</form>
Related
I have a search field in my app. I need to clone this search field with the same functions. One search field at the left side of the page and another, the same search field, at the right side of the page.
How I can make the clone using JS?
Below my JS code
document.querySelector('#city').addEventListener(click,'keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
and part of HTML code
<body>
<div class="jumbotron" id="jumbo">
<h2 class="text-center" id="th2">Weather</h2>
</div>
<div class="container" id="cont">
<div class="row">
<h2 class="text-center text-primary">Your City</h2>
<span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
<input type="text" name="city" id="city" class="form-control" placeholder="City Name">
<button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>
</div>
As an option, I would suggest to create some function or class that creates input and description nodes and append to whatever container id (or class) you pass to it. In html you would only need element with rowDiv id. Obviously you can tailor it to your needs, but it's just an idea.
I thought something like this:
// rough example based of your code
class citySearch {
constructor(parentContainerId) {
this.searchField;
this.displayArea;
this.setStage(parentContainerId);
this.hookListener();
}
setStage(parentContainerId) {
this.searchField = document.createElement('input');
this.displayArea = document.createElement('div');
var parentContainer = document.getElementById(parentContainerId)
parentContainer.appendChild(this.searchField);
parentContainer.appendChild(this.displayArea);
}
show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
hookListener() {
this.searchField.addEventListener('keypress', this.onClick.bind(this));
}
onClick(e) {
if (e.keyCode === 13) {
var city = this.searchField.value;
if (city !== '') {
fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=bb037310921af67f24ba53f2bad48b1d")
.then( async(res) => {
const data = await res.json();
var widget = this.show(data);
this.displayArea.innerHTML = widget;
this.searchField.value = '';
})
} else {
this.displayArea.innerHTML = "<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>";
}
}
}
}
var firstSearch = new citySearch('rowDiv');
var secondSearch = new citySearch('rowDiv');
Html
<div class="row form-group form-inline" id="rowDiv"></div>
Here is some sample code that allows 1 code base, 2 search boxes and keeps the two search boxes in sync.
const searchBoxes = () => document.getElementsByClassName('searchbox');
document.addEventListener('DOMContentLoaded', function() {
Array.from(searchBoxes()).forEach(element => {
console.log(element.id);
element.addEventListener('keyup', function(event) {
let text = event.target.value;
// This is just a demo
document.getElementById("searchResult").innerHTML = text;
// Loop other search boxes
Array.from(searchBoxes()).forEach(e => {
if (e.id != event.target.id) e.value = text;
});
// ANY CODE HERE TO APPLY SEARCH
});
});
});
.searchbox {
border: 1px solid black;
background-color: wheat;
}
#searchResult {
height: 100px;
width: 100px;
background-color: yellow;
font-weight: bold;
}
<div>
<span>Some Text Here</span>
<input id="search1" class="searchbox" type="text" />
</div>
<div id="searchResult">ALL MY PAGE STUFF</div>
<div>
<span>Some Text Here</span>
<input id="search2" class="searchbox" type="text" />
</div>
Script:-
<script type="text/javascript">
$(document).ready(function () {
var x = document.getElementById("currentPage").value;
if (x == null || x == "")
GetPage(parseInt(1));
else
GetPage(parseInt(x));
$('#pager').on('click', 'input', function () {
GetPage(parseInt(this.id));
document.getElementById("currentPage").value = parseInt(this.id);
});
});
function GetPage(pageIndex) {
//debugger;
$.ajax({
cache: false,
//url: "/EmailScheduler/",
url: '#(Url.RouteUrl("EmailScheduler"))',
type: "POST",
data: { "selectValue": pageIndex },
traditional: true,
dataType: "json",
success: function (data) {
//debugger;
$('#GridRows').empty();
$('#pager').empty();
var trHTML = '';
var htmlPager = '';
$.each(data.Customers, function (i, item) {
trHTML += ' <tbody class="table-hover"><tr>'
+ '<td class="text-left"><div class="checkbox" style="padding-left:50px;"><label><input type="checkbox" id=" ' + item.CustomerID + '" class="checkBoxClass"/></label></div></td>'
+ '<td class="text-left" id="tblFirstName"> ' + item.FirstName + '</td>'
+ '<td class="text-left" id="tblLastName"> ' + item.LastName + '</td>'
+ '<td class="text-left" id="tblEmailID"> ' + item.EmailID + '</td>'
+ '<td class="text-left" id="tblCustomerType"> ' + item.CustomerType + '</td>'
+ '<td class="text-left" id="tblCustomerDesignation" style="padding-left:40px;padding-right:30px;"> ' + item.CustomerDesignation + '</td></tr></tbody>'
});
$('#GridRows').append(trHTML);
if (data.Pager.EndPage > 1) {
htmlPager += '<ul class="pagination">'
if (data.Pager.CurrentPage > 1) {
htmlPager += '<li><input class="myButton" style="width:25px;height:25px;" type="button" id="1" style="font-weight:bold;" value="<<" /></li><li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage - 1) + '"value="<"></li>'
}
for (var page = data.Pager.StartPage; page <= data.Pager.EndPage; page++) {
htmlPager += '<li class="' + (page == data.Pager.CurrentPage ? "active" : "") + '"><input type="button" class="myButton" id="' + page + '" value="' + page + '"/></li>'
}
if (data.Pager.CurrentPage < data.Pager.TotalPages) {
htmlPager += '<li><input type="button" class="myButton" id="' + (data.Pager.CurrentPage + 1) + '" value=">"/></li><li><input type="button" class="myButton" id="' + (data.Pager.TotalPages) + '" value=">>"/></li>'
}
htmlPager += '</ul>'
}
$('#pager').append(htmlPager);
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
}
});
}
$(document).on('click', '#GridRows .checkBoxClass',
function () {
var cid = $(this).attr('id');
debugger;
var CustomerIDArray = [];
var hidCID = document.getElementById("hfCustomerID");
if (hidCID != null && hidCID != 'undefined') {
var CustID = hidCID.value;
CustomerIDArray = CustID.split("|");
var currentCheckboxValue = cid;
var index = CustomerIDArray.indexOf(currentCheckboxValue);
//debugger;
if (index >= 0) {
var a = CustomerIDArray.splice(index, 1);
//alert("a" + a);
}
else {
CustomerIDArray.push(currentCheckboxValue);
//alert('pushed value:' + CustomerIDArray);
}
hidCID.value = CustomerIDArray.join("|");
//alert('Final' + hidCID.value);
}
else {
alert('undefined');
}
});
$(document).on('click', '#cbSelectAll', function () {
if (this.checked) {
//$(':checkbox').each(function () {
$("#GridRows .checkBoxClass").each(function () {
//debugger;
this.checked = true;
var selectall = document.getElementsByClassName(".checkBoxClass");
var custid = $(this).attr('id');
console.log('custid' + custid);
var hidSelectAll = document.getElementById("hfSelectAll");
var hidCustomer = document.getElementById("hfCustomerID");
hidCustomer = '';
var str = 'Select All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$("#GridRows .checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var cid = $(this).attr('id');
console.log('cid' + cid);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'Select All + unselected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
else {
$(':checkbox').each(function () {
this.checked = false;
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'UnSelect All';
hidSelectAll.value = str;
console.log(hidSelectAll);
});
$(".checkBoxClass").change(function () {
if (!$(this).prop("checked")) {
$("#cbSelectAll").prop("checked", false);
var hidSelectAll = document.getElementById("hfSelectAll");
var str = 'unSelect All + selected values';
hidSelectAll.value = str;
console.log(hidSelectAll);
}
});
}
});
</script>
HTML:-
<div class="table-responsive" style="padding-left:20%;">
<table id="tCustomer" class="table-fill" style="float:left;">
<thead>
<tr>
<th class="text-left">
Select All
<div class="checkbox">
<input style="margin-left:15px;" type="checkbox" id="cbSelectAll" class="checkBoxClass"/>
</div>
</th>
<th class="text-left" style="padding-left:27px;">
First Name
</th>
<th class="text-left" style="padding-left:32px;">
Last Name
</th>
<th class="text-left" style="padding-left:40px;padding-right: 60px;">
Email-ID
</th>
<th class="text-left" style="padding-left:30px;padding-right: 40px;">
Customer Type
</th>
<th class="text-left" style="padding-left:15px;">
Customer Designation
</th>
</tr>
</thead>
</table>
<div id="GridRows" style="width:65%;">
</div>
</div>
<div id="pager"></div>
<input type="hidden" id="currentPage">
<input type="hidden" id="hfCustomerID"/>
<input type="hidden" id="hfSelectAll" />
In this When click on Select all checkbox then all values from should
be checked but when select all checked box is checked then only value
from current pagination got selected.
table contain is generated from ajax to avoid loss of checked value
while page load.
In your case
$(".checkBoxClass").prop('checked', true);
should work too.
The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements.
Read More: Here
In jquery you can achieve this by:
$('input[type="checkbox"]').prop('checked', true);
It will make all checkbox checked.
I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);
I'm working on a site where a user can create however many domains he wishes on a server. Each domain can belong to a group(this overall does nothing to the domain itself it's there for easier sorting).
A user can add/delete/modify each group separately.
I'm using a jQuery plugin called Spectrum so that a user can assign a color to each of his groups. See here.
I'm doing some ajax to dynamically update the groups(change the color/name). Everything is working great, except for one thing: the above mentioned plugin doesn't work properly for appended html(which I suppose is to be expected).
Normally for such a thing I'd reload the plugin, however I don't see any method in the documentation that would allow me to do that.
Is there some other way that I could reload it? Maybe some jQuery method? Bind to some event? Something?
Any help is appreciated.
function ajaxAddDomainGroup(group_color_add, group_name_add) {
$.ajax({
url: "<?= URL::route('domains_ajax_add_group'); ?>",
type: 'POST',
data: 'data[group_name]=' + group_name_add + '&data[group_color]=' + group_color_add,
success: function (data)
{
if(data.status == 'OK') {
$.notify('Group added successfully.', {
type: 'info',
delay: 120000
});
$('#js--groups_table tr:first').before(
'<tr>' +
'<td class="ccs-table__label" style="background-color: ' + data.data.group_color + '!important;"' + '>' + data.data.group_name + '</td>' +
' <td class="ccs-table__action js--groups_edit">' +
'<span class="icon-edit-ccs icon-ccs"></span>' +
'</td>' +
'<td class="ccs-table__action"><a id="delete_' + data.data.id + '" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>' +
'</tr><tr><td colspan="3"><div class="js--edit_info css-hide_edit_info box__controls">' +
'<div class="col-md-6"> <input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">' +
'</div><div class="col-md-6"><a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_' + data.data.id + '" href="#">Modify</a>' +
'<input class="js--spectrum-color-edit"/> <input type="hidden" class="js--group_color_edit" value="#000000"/> </div> </div> </td> ' +
'</tr>'
);
}
else {
$.notify('An error has occurred when trying to add the group.', {
type: 'info',
delay: 120000
});
}
}
});
}
function ajaxEditDomainGroup(group_name_edit, group_color_edit, group_id_edit) {
$.ajax({
url: "<?= URL::route('domains_ajax_edit_group'); ?>",
type: 'POST',
data: 'data[new_group_name]=' + group_name_edit + '&data[new_group_color]=' + group_color_edit + '&data[group_id]=' + group_id_edit,
success: function (data)
{
if(data.status == 'OK') {
$.notify('Group edited successfully.', {
type: 'info',
delay: 120000
});
$('#js--edit_' + group_id_edit).closest('tr').prev('tr').find('td:first-child').replaceWith(
'<td class="ccs-table__label" style="background-color: ' + group_color_edit + '!important;">' + group_name_edit + '</td>'
);
}
else {
$.notify('An error has occurred when trying to edit the group.', {
type: 'info',
delay: 120000
});
}
}
});
}
$('body').on('click','.js--group_edit', function() {
var group_name_edit = $(this).closest('td').find('.js--input_group_name_edit').val();
var group_color_edit = $(this).closest('td').find('.js--group_color_edit').val();
var group_id_edit = parseInt($(this).attr('id').replace(/[^\d]/g, ''), 10);
if($.trim(group_color_edit) == '') {
alert('The group color is required.');
return false;
}
else if( $.trim(group_name_edit) == '') {
alert('The group name is required.');
return false;
}
ajaxEditDomainGroup(group_name_edit, group_color_edit, group_id_edit);
});
Relevant html:
#foreach($domain_groups as $key => $domain_info)
<tr>
<td class="ccs-table__label"
#if(isset($domain_info['color']) && $domain_info['color'] != ''))
style="background-color: {{ $domain_info['color'] }}!important;"
#endif
>{{ $domain_info['group_name']; }}
</td>
<td class="ccs-table__action js--groups_edit">
<span class="icon-edit-ccs icon-ccs"></span>
</td>
<td class="ccs-table__action"><a id="delete_{{ $domain_info['id'] }}" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>
</tr>
<tr>
<td colspan="3">
<div class="js--edit_info css-hide_edit_info box__controls">
<div class="col-md-6">
<input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">
</div>
<div class="col-md-6">
<a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_{{ $domain_info['id'] }}" href="#">Modify</a>
<input class="js--spectrum-color-edit"/>
<input type="hidden" class="js--group_color_edit" value="#000000"/>
</div>
</div>
</td>
</tr>
#endforeach
Spectrum init and such:
$(".js--spectrum-color-edit").spectrum({
color: '#000',
showAlpha: true,showInput: true,
// Set the hext value of the color to a hidden input
move: function(color){
$(this).closest('td').find('.js--group_color_edit').val(color.toHexString());
}
});
I realize this isn't the most easy-on-the-eyes code. Odds are it's gonna be refactored in the future using angular or something like that.
You need to apply spectrum to any newly created matching elements within the dynamically loaded rows:
var $newtr = $('<tr>' +
'<td class="ccs-table__label" style="background-color: ' + data.data.group_color + '!important;"' + '>' + data.data.group_name + '</td>' +
' <td class="ccs-table__action js--groups_edit">' +
'<span class="icon-edit-ccs icon-ccs"></span>' +
'</td>' +
'<td class="ccs-table__action"><a id="delete_' + data.data.id + '" class="ccs-groups_delete" href="#"><span class="icon-delete-ccs icon-ccs"></span></a></td>' +
'</tr><tr><td colspan="3"><div class="js--edit_info css-hide_edit_info box__controls">' +
'<div class="col-md-6"> <input class="input--block js--input_group_name_edit" type="text" placeholder="New group name">' +
'</div><div class="col-md-6"><a class="btn btn--action btn--default js--group_edit btn__text" id="js--edit_' + data.data.id + '" href="#">Modify</a>' +
'<input class="js--spectrum-color-edit"/> <input type="hidden" class="js--group_color_edit" value="#000000"/> </div> </div> </td> ' +
'</tr>');
$('#js--groups_table tr:first').before($newtr)
$(".js--spectrum-color-edit", $newtr).spectrum({
color: '#000',
showAlpha: true,
showInput: true,
// Set the hext value of the color to a hidden input
move: function (color) {
$(this).closest('td').find('.js--group_color_edit').val(color.toHexString());
}
});
I have the following JQuery script :
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>transactions/user_requests",
dataType: "JSON",
success: function(request) {
request_list = $('#request_list').empty();
if (request === null) {
request_list.append("<p>No Active Requests</p>");
}
else {
$.each(request, function(i, request) {
request_list.append('<ul><a class="request_list" id="request_list" href="#active_request_list">' + request.department_name + '</a></ul>');
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>transactions/user_requests_detials",
dataType: "JSON",
success: function(request_list) {
request_list_details = $('#request_list_details').empty();
if (request_list === null) {
request_list_detials.append("<ul>No Active Requests</ul>");
} else {
$.each(request_list, function(i, request_list) {
request_list_details.append('<dt span="font_color:white !important;">' + request_list.department_name + '</dt>\n\
<dd><label style="float:left !important;">Commodity Name:</label><span style="color:red !important;">' + request_list.commodity_name + '</span></dd>\n\
<dd><label style="float:left !important;"> Quantity Requested:</lable><span style="color:red !important;">' + request_list.total_quantity_requested + '</span></dd>\n\
<dd><label style="float:left !important;">Request Order ID:</label><span style="color:red !important;">' + request_list.request_order_id + '</span></dd>\n\
<dd><label style="float:left !important;">Date Requested : </label><span style="color:red !important;">' + request_list.date_added + '</span></dd> \n\
<a class="approve" id="approve" href="#stock_details">Approve </a>');
});
}
},
error: function(data) {
}
});
});
}
},
error: function(data) {
// alert('An error occured, kindly try later');
}
});
}, 2000);
});
</script>
<div class='request'>
<p>Request List</p><br>
<ul id='request_list'></ul>
</div>
The above loads a list of all requests made and a link for approving the details of the requests, when the link is clicked, the following script is supposed to run:
<script>
$(document).ready(function() {
alert('Alert!!!');
$('.approve').click(function() {
alert('Alert!!');
request_order_id = $('#request_order_id').val();
alert(request_order_id);
html1 = '';
htmlhead1 = '';
$.ajax({
type: "GET",
url: "<?php echo base_url();?>transactions/to_be_issued_details/" + request_order_id,
dataType: "json",
success: function(data) {
for (i = 0; i < data.length; i++) {
html1 += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="' + data[i].commodity_name + '"/></td>\n\
<td><input type="text" class="SmallInput" id="batch_no' + i + '" name="batch_no[]" value="' + data[i].batch_no + '"/></td>\n\
<td><input type="text" class="SmallInput" id="total_quantity_requested' + i + '" name="total_quantity_requested[]" value="' + data[i].total_quantity_requested + '"/></td>\n\
<td><input type="text" id="request_order_id' + i + '" name="request_order_id[]" value="' + data[i].request_order_id + '"/></td>\n\
<td><input type="text" class="SmallInput" id="total_quantity' + i + '" name="total_quantity[]" value="' + data[i].total_quantity + '"/></td>\n\
<td><input type="text" class="SmallInput" id="department' + i + '" name="department[]" value="' + data[i].department + '"/></td>\n\
<td><input type="text" class="SmallInput" id="user_name' + i + '" name="user_name[]" value="' + data[i].user_name + '"></td> \n\
<td></td><td></td></tr> ';
}
htmlhead1 += '\n\
<th>Commodity Name</th>\n\
<th>Batch Number</th> \n\
<th> Category</th> \n\
<th>Units per Pack </th> \n\
<th>No of Packs</th>\n\
<th>Total Quantity</th>\n\
';
$('#thead1').empty();
$('#tbody1').empty();
$('#thead1').append(htmlhead1);
$('#tbody1').append(html1);
},
error: function(data) {
}
})
});
});
</script>
Which is supposed to give me more details about the request, when I click the Approve button, the click function does not respond at all, which is the best way I can approach this problem?
This is because you are assigning the click event to .approve before it even exists.
What you want is to do this:
$("body").on("click", ".approve", function () {
//Your code
});
This way, using delegation, you assign a listener to the body (but preferably you should assign it to a less generic container like #request_list_details if it exists at the time you create the event listener) and the click event "bubbles up" trying to find an element with the class approve. This way you can dynamically add elements with that class and they still will respond to that event.
You can read more about it at the official jQuery API Documentation page.
Using delegation with on():
$('#request_list_details').on('click','.approve',function(){
//...
});