jQuery DataTable firing multiple times while trying to hide columns - javascript

Update Here is another example, just a few lines of code... the alert pops up twice!
$(document).ready( function ()
{
var x = $('#example').dataTable(
{
fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull )
{
// Row click
$(nRow).on('click', function()
{
alert(aData);
console.log('Row Clicked. Look I have access to all params, thank You closures.', this, aData, iDisplayIndex, iDisplayIndexFull);
});
}
});
x.fnSetColumnVis( 0, false ); //This line of code causes the click to be called twice
});
I am trying to have a jQuery DataTable that I can click. I also need to hide a few columns...
My thought process was this...
Define a javascript variable which I called tb and assign it equal to the jQuery $('mytable').dataTable(...); and then go and use tb to remove the columns I don't need with a method call like this... tb.fnSetColumnVis( 0, false );. The problem is, if I do that, my onclick method gets called multiple times! So I had to comment that out, but now all my columns are visible.
So I need a way to hide columns and also define a click.
var tb = $('#myrecords-table-table').dataTable(
{
fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull )
{
// Row click
$(nRow).on('click', function()
{
$( "#tabsright" ).tabs({ active : 0 });
$("#newrecordform").show();
$("#nr_name").val(aData[2]);
$("#create_ri_reportid").val(aData[0]);
//Update summary field
getSummary(aData);
var i;
var select = document.getElementById("nr_s_actors");
for(i=0;i<select.options.length;i++)
{
select.options[i].selected=false;
}
$("#nr_s_actors").multiselect("refresh");
//Get the actors that are selected
$.ajax(
{
url: 'phpscripts/getreportrelations.php',
data: 'reportid=' + aData[0],
dataType: 'json',
success: function(data)
{
$.each(data,function(index,value)
{
var id="id_actor_"+value[0];
document.getElementById(id).selected = true;
$("#nr_s_actors").multiselect("refresh");
});
},
error: function (header, status, error)
{
console.log('ajax answer post returned error ' + header + ' ' + status + ' ' + error);
}
});
//TODO find out why this is being called multiple times. Most likely because jQuery script is being included multiple times
//TODO find out how to clear the screen
$.ajax(
{
url: 'phpscripts/getreportinstances.php',
data: 'reportid=' + aData[0],
dataType: 'json',
success: function(data)
{
/*while(document.getElementById("current_ris_div").firstNode())
{
document.getElementById("current_ris_div").removeChild(document.getElementById("current_ris_div"));
}*/
for(var y in data)
{
console.log(data[y],"is the y in data");
var element = document.createElement("DIV");
element.name = "reportinstance_"+y;
element.id = "reportinstance_"+y;
element.innerHTML = data[y]['summary']+"<br/>";
element.innerHTML = element.innerHTML + data[y]['location']+"<br/>";
element.innerHTML = element.innerHTML + data[y]['summary']+"<br/>";
for(var x in data[y]['people'])
{
element.innerHTML = element.innerHTML + data[y]['people'][x] +"<br/>";
}
for(var x in data[y]['behavior'])
{
element.innerHTML = element.innerHTML + data[y]['behavior'][x] +"<br/>";
}
for(var x in data[y]['media'])
{
element.innerHTML = element.innerHTML + "<image src=\""+data[y]['media'][x] +"\"/><br/>";
}
document.getElementById("current_ris_div").appendChild(element);
}
/*$.each(data,function(index,value)
{
console.log(data);
var element = document.createElement("DIV");
element.name = "reportinstance_"+index;
element.id = "reportinstance_"+index;
element.innerHTML = value['summary']+"<br/>";
element.innerHTML = element.innerHTML + value['location']+"<br/>";
element.innerHTML = element.innerHTML + value['summary']+"<br/>";
for(var x in value['people'])
{
element.innerHTML = element.innerHTML + value['people'][x] +"<br/>";
}
for(var x in value['behavior'])
{
element.innerHTML = element.innerHTML + value['behavior'][x] +"<br/>";
}
for(var x in value['media'])
{
element.innerHTML = element.innerHTML + "<image src=\""+value['media'][x] +"\"/><br/>";
}
document.getElementById("current_ris_div").appendChild(element);
});*/
},
error: function (header, status, error)
{
console.log('ajax answer post returned error ' + header + ' ' + status + ' ' + error);
}
});
//Now set the media type
var ii;
var selecti = document.getElementById("nr_s_mediatypes");
for(ii=0;ii<selecti.options.length;ii++)
{
selecti.options[ii].selected=false;
}
console.log("What index should I use", aData);
var iidd = "id_mediatype_"+aData[4];
console.log(iidd);
document.getElementById(iidd).selected = true;
$("#nr_s_mediatypes").multiselect("refresh");
});
}
});
//tb.fnSetColumnVis( 0, false );
//tb.fnSetColumnVis( 1, false );
//tb.fnSetColumnVis( 4, false );

I am not sure why this is happening. Your example code is way too long to read.
Use this Plunker as a base for further questions and drop out all of the stuff of your code that does nothing.
As you can see the Plunker works. I did go a step ahead and changed click to bind and also added an unbind (just to be on the safe side, but the script works without it, too)
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//This is not realy necessary
$(nRow).unbind('click');
$(nRow).bind('click', function() {
alert ('clicked');
});
}

The solution I ended up implementing was using this thing "aoColumns". What I don't understand about jQuery is how we can just thrown things in like "aoColumns" and fnRowCallback all with different syntax! It doesn't make any sense and there are no patterns!
var tb = $('#myrecords-table-table').dataTable(
{
"aoColumns":
[
{"bVisible":false},
{"bVisible":false},
null,
null,
null
],
fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull )
{
// Row click
$(nRow).on('click', function()
{
$( "#tabsright" ).tabs({ active : 0 });
$("#newrecordform").show();
$("#nr_name").val(aData[2]);
$("#create_ri_reportid").val(aData[0]);
...

Related

jQuery table sorter not working for values that are fetched by AJAX

I have implemented jQuery tablesorter in my project.
My table consist of input textfields of which some are populated by ajax. Table sorting is working perfectly for the input fields that are entered by user, but the input fields that are populated from database using ajax are not sorting properly.
My code :
jQuery(function () {
jQuery('#tablesorter-demo').tablesorter({
widgets: ['zebra', 'stickyHeaders'],
headers: {
2: {
sorter: 'inputs'
},
3: {
sorter: 'inputs'
},
5: {
sorter: 'inputs'
}
}
});
});
jQuery.tablesorter.addParser({
id: 'inputs',
is: function (s) {
return false;
},
format: function (s, table, cell, cellIndex) {
var jQueryc = jQuery(cell);
// return 1 for true, 2 for false, so true sorts before false
if (!jQueryc.hasClass('updateInput')) {
jQueryc
.addClass('updateInput')
.bind('keyup', function () {
console.log(table);
jQuery(table).trigger('updateCell', [cell, false]); // false to prevent resort
});
}
return jQueryc.find('input[type="text"]').val();
},
type: 'text'
});
My AJAX function :
jQuery('.bulkupload').keyup(function () {
check = 1;
jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F");
var part_no1 = jQuery("#" + jQuery(this).attr("id")).val();
var fieldcount = part_no1.toString().length;
var thenum = jQuery(this).attr("id").replace(/^\D+/g, '');
if (jQuery('#qty' + thenum).val() == '') {
jQuery('#qty' + thenum).val('Enter Quantity');
jQuery('#qty' + thenum).css("color", "#DF1F26");
}
var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails";
jQuery.ajax({
type: "POST",
url: url1,
data: {
part_no1: part_no1
},
success: function (response) {
if (response == "check") {
jQuery('#item_name' + thenum).val("Not Found");
jQuery('#item_desc' + thenum).val("Not Found");
jQuery('#av_qty' + thenum).css("color", "#DF1F26");
jQuery('#item_name' + thenum).css("color", "#DF1F26");
jQuery('#item_desc' + thenum).css("color", "#DF1F26");
jQuery('#brand_name' + thenum).css("color", "#DF1F26");
}
else {
var result1 = jQuery.parseJSON(response);
jQuery('#item_name' + thenum).val(result1.prodname1);
jQuery('#item_desc' + thenum).val(result1.productdescription1);
jQuery('#brand_name' + thenum).val(result1.brand);
jQuery('#av_qty' + thenum).css("color", "#DF1F26");
jQuery('#item_name' + thenum).css("color", "#DF1F26");
jQuery('#item_desc' + thenum).css("color", "#DF1F26");
jQuery('#brand_name' + thenum).css("color", "#DF1F26");
if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) {
jQuery('#av_qty' + thenum).val("Not in Stock");
} else {
jQuery('#av_qty' + thenum).val(result1.stock);
}
jQuery("#tablesorter-demo").trigger('updateCell');
}
}
});
});
From the options & widgets that you are using, it appears that you are actually using my fork of tablesorter instead of the original plugin.
Anyway, the widget you created for the input parser is binding to the cell
jQuery(cell).bind('keyup', function () { ... }
but when the table is sorted, the cells are removed from the tbody causing any event bindings to break. The way to get around this problem is to use delegated event binding on the tbody (but done outside of the widget format function because it only needs to be done once).
jQuery('table tbody').on('keyup', 'input', function(e) {
var $input = $(e.target);
...
}
Additionally, when you update a lot of inputs from your ajax call, it would be better to just update them all at once (.trigger('update')), otherwise you're using the updateCell method too much and likely causing the entire process to take longer than necessary.
This demo uses a very similar method to update checkboxes within a table, so it should be fairly straight-forward to convert it to make it work with input values - if you have trouble, just post here and I'll help.
// checkbox parser
$.tablesorter.addParser( {
id: 'checkbox',
is: function( s ) {
return false;
},
format: function( s, table, cell ) {
var $c = $( cell ).find( 'input' );
return $c.length ? $c.is( ':checked' ) ? 1 : 2 : s;
},
type: 'numeric'
});
$( function() {
// using .on() which requires jQuery 1.7+
$( 'table' ).on( 'tablesorter-initialized', function() {
// class name to add on tr when checkbox is checked
var highlightClass = 'checked',
// resort the table after the checkbox is modified?
resort = true,
// if a server side database needs to be updated, do it here
serverCallback = function( table, inputElement ) {},
$table = $( this ),
c = this.config,
wo = c && c.widgetOptions,
// include sticky header checkbox; if installed
$sticky = c && wo.$sticky || '',
doChecky = function( c, col ) {
$table
.children( 'tbody' )
.children( 'tr:visible' )
.children( 'td:nth-child( ' + ( parseInt( col, 10 ) + 1 ) + ' )' )
.find( 'input' )
.each( function() {
this.checked = c;
$( this ).trigger( 'change' );
});
};
$table
.children( 'tbody' )
.on( 'change', 'input', function() {
// ignore change if updating all rows
if ( $table[0].ignoreChange ) { return; }
var col, $this = $( this );
$this.closest( 'tr' ).toggleClass( highlightClass, this.checked );
$this.trigger( 'updateCell', [ $this.closest( 'td' ), resort ] );
// if your server side database needs more parameters, add them here sent to the callback
serverCallback( $table[0], this );
// uncheck header if any checkboxes are unchecked
if ( !this.checked ) {
$table.add( $sticky ).find( 'thead input' ).prop( 'checked', false );
}
})
.end()
.add( $sticky )
.find( 'thead input' )
// Click on checkbox in table header to toggle all inputs
.on( 'change', function() {
// prevent updateCell for every cell
$table[0].ignoreChange = true;
var c = this.checked,
col = $( this ).closest( 'th' ).attr( 'data-column' );
doChecky( c, col );
// update main & sticky header
$table.add( $sticky ).find( 'th[data-column=' + col + '] input' ).prop( 'checked', c );
$table.children( 'tbody' ).children( 'tr:visible' ).toggleClass( highlightClass, c );
// update all at once
$table[0].ignoreChange = false;
$table.trigger( 'update', [ resort ] );
})
.on( 'mouseup', function() {
return false;
});
});
});
I should also note that when your ajax call is done and the changes have been applied, that is when an "update" method should be triggered, not "updateCell".
Lastly, there is an existing input-select parser but it doesn't include a method to prevent massive updateCell method calls versus updating the table all at once.
Table sorting is working perfectly for the input fields that are
entered by user, but the input fields that are populated from database
using ajax are not sorting properly.
This is because when you load that page, jQuery library & table sorter libraries are loaded at that time and table sorter functionality is added to your table at that time.
tablesorter-demo
Here is the example..
<script type="text/javascript" src="/path/to/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script>
$(document).ready(function()
{
$("#tablesorter-demo").tablesorter();
}
);
And when contents are loaded via AJAX, this table sorting property has already been added to the table & it is not applied to the new data fetched by the AJAX function because AJAX function worked after the initial page load. So all you have to do is add the table sorter property
$("#tablesorter-demo").tablesorter();
just above the line
jQuery("#tablesorter-demo").trigger('updateCell');
I hope this helps..because it worked for me when I faced the same problem while loading contents via AJAX & trying to sort 'em.
Try this...
jQuery('.bulkupload').keyup(function () {
check = 1;
jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F");
var part_no1 = jQuery("#" + jQuery(this).attr("id")).val();
var fieldcount = part_no1.toString().length;
var thenum = jQuery(this).attr("id").replace(/^\D+/g, '');
if (jQuery('#qty' + thenum).val() == '') {
jQuery('#qty' + thenum).val('Enter Quantity');
jQuery('#qty' + thenum).css("color", "#DF1F26");
}
var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails";
ajaxfunction(url1);
function ajaxfunction(url1)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
if (response == "check") {
jQuery('#item_name' + thenum).val("Not Found");
jQuery('#item_desc' + thenum).val("Not Found");
jQuery('#av_qty' + thenum).css("color", "#DF1F26");
jQuery('#item_name' + thenum).css("color", "#DF1F26");
jQuery('#item_desc' + thenum).css("color", "#DF1F26");
jQuery('#brand_name' + thenum).css("color", "#DF1F26");
}
else {
var result1 = jQuery.parseJSON(response);
jQuery('#item_name' + thenum).val(result1.prodname1);
jQuery('#item_desc' + thenum).val(result1.productdescription1);
jQuery('#brand_name' + thenum).val(result1.brand);
jQuery('#av_qty' + thenum).css("color", "#DF1F26");
jQuery('#item_name' + thenum).css("color", "#DF1F26");
jQuery('#item_desc' + thenum).css("color", "#DF1F26");
jQuery('#brand_name' + thenum).css("color", "#DF1F26");
if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) {
jQuery('#av_qty' + thenum).val("Not in Stock");
} else {
jQuery('#av_qty' + thenum).val(result1.stock);
}
jQuery("#tablesorter-demo").trigger('updateCell');
$("#tablesorter-demo").tablesorter();
}
}
}
xmlhttp.open("GET",url1,true);
xmlhttp.send();
}
});

Applying jquery autocomplete to the json object

I am trying to make trigger based auto-complete in textarea using jQuery autocomplete. (when you type "#", the autocomplete starts).
Till now I am able to implement it for the case where the data is an array.
HTML
<textarea class="searchBox" rows="10" cols="20"></textarea>
jQuery
var triggered = false; // By default trigger is off
var trigger = "#"; // Defining the trigger
$(".searchBox").autocomplete({
source: [ // defining the source
"A",
"Apple",
"S",
"D",
"q"],
search: function () { // before search, if not triggerred, don't search
if (!triggered) {
return false;
}
},
select: function (event, ui) { // invokes the data source, search starts
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) + ui.item.value;
triggered = false;
return false;
},
focus: function (event, ui) {
return false;
},
minLength: 0 // minimum length of 0 require to invoke search
});
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
Here is its fiddle : http://jsfiddle.net/5x9ZR/4/
Now I was trying to implement it when the data is in the form of json object.
But the autocomplete isn't responding with results.
I tried it bare. ( without any trigger mechanism ). It isnt displaying any results.
Code:
HTML
<textarea class="searchBox" rows="10" cols="20"></textarea>
jQuery
var triggered = false; // By default trigger is off
var trigger = "#"; // Defining the trigger
var data = [{
"name": "needmoreinfo",
"email": "needmoreinfo"
}, {
"name": "explained",
"email": "explained"
}, {
"name": "raypipeline09",
"email": "raypipeline09"
}];
$(".searchBox").autocomplete({
source: data,
search: function () { // before search, if not triggred, don't search
if (!triggered) {
return false;
}
},
select: function (event, ui) { // invokes the data source, search starts
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) + ui.item.email;
triggered = false;
return false;
},
focus: function () {
return false;
},
minLength: 0 // minimum length of 0 require to invoke search
})._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
$('.searchBox').keyup(function (e) {
if (e.keyCode == 38 || e.keyCode == 40) {
return;
}
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
} else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});
Here is the fiddle of what I tried. http://jsfiddle.net/HGxSX/
Where I am going wrong ? Please explain.
Solved it.
There is a bug in the jQuery due to which this was happening.
The data has to be in the form of "label" and "value". Otherwise it doesn't works.
Thanks to anyone who tried.
Here is the final working fiddle : http://jsbin.com/qakefini/7
PS: I tried making account on the jQuery website but could not login. Its saying some redirection problem. If someone has an account, please report the bug.
Doesnt seem to like json strings without a label - it uses this on its keyup to check values..
see your updated/destroyed fiddle:
http://jsfiddle.net/jFIT/HGxSX/1/
var data = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png",
name: "needmoreinfo",
email: "needmoreinfo"
},{
and in your autocomplete function the renderitem was missing some things, you should update the version of jquery your using btw.. seems alot simpler in 1.9:
}).data( "autocomplete" )._renderItem = function( ul, item ) { console.log('wut');
return $( "<li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.email + "<br>" + item.name + "</a>" )
.appendTo( ul );
};

Attaching multiple events to single function in jQuery

I'm looking for the opposite of that everyone's been looking for. I have this anonymous jQuery function that I want to keep that way, but I want to attach multiple events handlers to it on different events (two events exactly).
When the textarea has text inside it changed (keyup)
When document is clicke (click).
I know that grabbing the callback function and putting it in a function declaration, then using the function on both cases would do the job, but is there something around that wont require me to put the callback function in a normal function and just leave it as is?
This is the code I currently have:
urls.keyup(function(){
delay('remote', function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
if (has_lbrs)
{
urls_array = urls.val().split("\n");
for (var i = 0; i < urls_array.length; i++)
{
if (!validate_url(urls_array[i]))
{
urls_array.splice(i, 1);
continue;
}
}
}
else
{
if (!validate_url(urls.val()))
{
display_alert('You might have inserted an invalid URL.', 'danger', 3000, 'top');
return;
}
}
final_send = (has_lbrs && urls_array.length > 0) ? urls_array : urls.val();
if (!final_send)
{
display_alert('There went something wrong while uploading your images.', 'danger', 3000, 'top');
return;
}
var template = '<input type="text" class="remote-progress" value="0" />';
$('.pre-upload').text('').append(template);
$('.remote-progress').val(0).trigger('change').delay(2000);
$('.remote-progress').knob({
'min':0,
'max': 100,
'readOnly': true,
'width': 128,
'height': 128,
'fgColor': '#ad3b3b',
'bgColor': '#e2e2e2',
'displayInput': false,
'cursor': true,
'dynamicDraw': true,
'thickness': 0.3,
'tickColorizeValues': true,
});
var tmr = self.setInterval(function(){myDelay()}, 50);
var m = 0;
function myDelay(){
m++;
$('.remote-progress').val(m).trigger('change');
if (m == 100)
{
// window.clearInterval(tmr);
m = 0;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote',
urls: JSON.stringify(final_send),
thumbnail_width: $('.options input[checked]').val(),
resize_width: $('.options .resize_width').val(),
album_id: $('#album_id').val(),
usid: $('#usid').val(),
},
success: function(data) {
// console.log(data); return;
var response = $.parseJSON(data);
if (response)
{
$('.middle').hide();
$('.remote-area').hide();
window.clearInterval(tmr);
}
if ('error' in response)
{
//console.log(response.error);
if (!$('.top-alert').is(':visible'))
{
display_alert(response.error, 'danger', 3000, 'top');
}
return;
}
if (!target.is(':visible'))
{
target.show().addClass('inner');
}
else
{
target.addClass('inner');
}
for (var key in response)
{
var image_url = response[key];
var thumb_uri = image_url.replace('/i/', '/t/');
var forum_uri = '[img]' + image_url + '[/img]';
var html_uri = '<a href="' + image_url + '">' + image_url + '</a>';
var view_url = image_url.replace(/store\/i\/([A-Za-z0-9]+)(?=\.)/i, "image/$1");
view_url = strstr(view_url, '.', true);
// Append the upload box
target.append(upload_box(key));
// Hide knob
$('.knobber').hide();
// Put the image box
putImage($('.' + key), view_url, image_url, thumb_uri, forum_uri, html_uri);
}
},
});
}
}, 2000); // Delay
}); // Remote upload
How do I make this code run on document click as well?
Thank you.
As you yourself has said in you question, the answer is to create an external named reference to the callback function and use it as the callback.
Like
jQuery(function () {
function callback(e) {
console.log('event2', e.type);
}
$('input').keyup(callback);
$(document).click(callback)
})
But since you have asked for a different style have a look at, it essentially does the same as the above one
jQuery(function () {
var callback;
$('input').keyup(callback = function (e) {
console.log('event', e.type);
});
$(document).click(callback)
})
Demo: Fiddle

Ajax File Upload Not Working for IE8

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.

how to change the text color using using jquery

function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val();
var targetIndex = $("#lstCodelist").val();
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
FinishAjaxLoading();
var x = $("#lstAvailableCode").val();
$("#lstCodelist").val(x);
$("#lstCodelist").val(x).css("background-color", "#ffffff");
}
});
Here I am trying to adding one item from lstAvailableCode list box to lstCodelist box. after adding into lstCodelist box I am trying to change the textcolor to yellow or some other color.
on my success message i wrote something like this. But I am not able to change the color of the text even I am not able to change the backgroud color of that list box. is that something I am doing wrong here?
here is my lstCodelist box code.
<select id="lstCodelist" size="17" name="lstCodelist" style="width:100%;height:280px;background-color:#EFEFFB;"></select>
$.fn.fillSelectDD = function (data) {
return this.clearSelectDD().each(function () {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
});
}
});
}
$("#lstCodelist").val(x).css("background-color", "#ffffff");
should be
$("#lstCodelist").css("background-color", "#ffffff");
.val() returns a value, not the original jQuery object.
To change the font color, you wold use:
$("#lstCodelist").css("color", "#00ffff");
$("#lstCodelist").val(x).css("background-color", "#ffffff");
should be
$("#lstCodelist").css("background-color", "#ffffff");
Otherwise you're trying to set a css property on whatever string/number the .val() call returns, and NOT on the actual page element that the value's coming from.

Categories