Not able to call a jQuery function - javascript

I am trying to get the file input preview working.
I have a jquery script which works fine when I call the function normally.
$('#images').on("change", previewImages);
This works.
But when I put the call to the same function differently like following
$('#images').on("change", function(){
previewImages();
});
This doesn't work.
I need to write an if else statement to call a different function on else.

Valid question
Reason: this happens because of this which refers to file element when you are using first approach but in case of second approach this is referring to window element in which it is called. So pass this to function and your question is solved.
$('#images').on("change", function(e) {
/* issue is with this */
previewImages(e, this);
});
var count = 0;
function previewImages(evt, cur) {
var $fileUpload = $("input#images[type='file']");
count = count + parseInt($fileUpload.get(0).files.length);
if (parseInt($fileUpload.get(0).files.length) > 7 || count > 6) {
alert("You can only upload a maximum of 6 files");
count = count - parseInt($fileUpload.get(0).files.length);
evt.preventDefault();
evt.stopPropagation();
return false;
}
$("#taskbar").css("height", "auto");
var $preview = $('#preview').empty();
if (cur.files) $.each(cur.files, readAndPreview);
function readAndPreview(i, file) {
// if (!/\.(jpe?g|png|gif|mp4)$/i.test(file.name)){
// return alert(file.name +" is not an image");
// }
var reader = new FileReader();
$('#preview img').addClass('img-responsive');
$(reader).on("load", function() {
$preview.append($("<img/>", {
src: this.result,
height: 100
}));
});
reader.readAsDataURL(file);
}
}

Create a prePreviewImages function, and use that in your first approach. Inside that function, use the if-statement and call previewImages() or your other function.

The following should do..
$('#images').change(function(e) {
if(e == "some condition"){ // if else goes here
previewImages();
}else {
SomeOtherFun();
}
});

Both ways seem to work for me on the JSFiddle. Are you sure it is not a
browser compatibility issue?
If not are you getting errors logged in the console under developer tools?

Related

Using a variable inside a input check in JS

The input named alternativa-*** will have the *** changed in the PHP that comes before. I'm not using a form on PHP only a onClick statement calling the respondeQuestao function. But this code seems to not work. Someone have any suggestion.
$(document).ready(function() {
function respondeQuestao(qid,resposta) {
var alternativa = document.getElementsByName('input[name = "aternativa-"' + qid ']:checked').value;
document.getElementById("demo").innerHTML = 5 + 6;
if(alternativa==resposta) {
$("#botao-questao"+qid).hide();
};
if(alternativa!=resposta) {
};
};
})
Defining a function within the jQuery Ready statement limits the accessibility - define it outside of the jQuery Ready statement but call it when you need it.
function respondeQuestao(qid, resposta) {
var alternativa = $("INPUT[name^='alternativa-']:checked").val();
$("#demo").html(5+6);
if (alternativa == resposta) {
$("#botao-questro" + qid).hide()
} else {
//
}
}
Call the function inside jQuery:
$(function() {
respondeQuestao("id", 11);
});
I hope this helps.

Why my JavaScript function is executing uncertainly if i add an alert()?

I wrote the function below to get the length of a listbox with the id courselessons. The problem is that when I comment the alert() the function changecheckbox works only once.
If I remove the alert it works fine. But I don't want to have an alert on every single click.
The selOpts shows correct content only for the first time.
JavaScript:
function changecheckbox() {
//alert("function called...");
var selOpts = document.getElementById("courselessons").length();
alert(selOpts);
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop('disabled', true).prop("checked", false);
}
}
function addItem() {
if (seltask == undefined || seltask.length === 0) {
return;
}
var lessonsDropdown = $('#courselessons');
lessonsDropdown.empty();
$("#tasks option:selected").appendTo("#coursetasks");
$("#coursetasks option").attr("selected", false);
if (seltask.length > 0) {
cacheToken = new Date().getTime();
// retrieve data using a Url.Action() to construct url
$.getJSON('#Url.Action("AddTaskToCourse")', {
task: seltask,
lesson: lesson,
_: cacheToken
});
$.getJSON('#Url.Action("UpdateLessonInCourse")', {
_: cacheToken
}).done(function (data) {
//re-enable tasks drop down
//for each returned tasks
$.each(data, function (i, lessons) {
//Create new option
var test = $('<option />').html(lessons);
//append tasks taskss drop down
lessonsDropdown.append(test);
});
seltask = null;
});
}
changecheckbox();
}
HTML:
<button type="button" id="btnAdd" onclick="addItem(); changecheckbox();">Add Item</button>
Try using like this,
function changecheckbox() {
//alert("function called...");
var selOpts = $("courselessons").find('option').length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop({'disabled':true, 'checked':false});
}
}
or you can do like this ,
$("#btnAdd").click(function(e){
e.preventDefault();
var selOpts = $("#courselessons").find('option').length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop({'disabled':true, 'checked':false});
}
});
The code inside addItem() is making a GET request to a resource asynchronously. This means the code which comes after this function to be execute will not wait for its execution to get complete.
When I uncomment the alert it works fine.
That is because as the alert() is built in, it halts the execution of script until user interaction. This gave the time addItem() needs and everything seems to work.
Fortunately, there are solutions available to handle this situation.
Promise.
Rearrange your code to work with callbacks.
Under the covers, $.getJSON is shorthand for making a GET request using ajax with datatype = 'json'and it returns a promise object which basically tells that please wait honey, i will give you something which could be a success or a failure but sometime later.
So yes, you can easily call the function inside the done().
NOTE: These things have been explained pretty well on web so i will not reinvent the wheel :)
Keeping the things simple...
function addItem() {
// Rest of the code...
if (seltask.length > 0) {
cacheToken = new Date().getTime();
// retrieve data using a Url.Action() to construct url
$.getJSON('#Url.Action("AddTaskToCourse")', {
task: seltask,
lesson: lesson,
_: cacheToken
});
$.getJSON('#Url.Action("UpdateLessonInCourse")', {
_: cacheToken
}).done(function (data) {
//re-enable tasks drop down
//for each returned tasks
$.each(data, function (i, lessons) {
//Create new option
var test = $('<option />').html(lessons);
//append tasks taskss drop down
lessonsDropdown.append(test);
});
seltask = null;
changecheckbox();
});
}
}
After this setup, you should remove the changecheckbox() call from the button onclick otherwise it would make it execute twice.
Remove the options, and take the id of select <select id="mySelect"> example:
var selOpts = document.getElementById("mySelect").length;
and your code will be
function changecheckbox() {
//alert("function called...");
var selOpts = document.getElementById("courselessons").length;
if (selOpts > 0) {
$('#taskassignment').prop('disabled', false);
}
else {
$('#taskassignment').prop('disabled', true);
$("#taskassignment").prop("checked", false);
}
}

synchronise code in javascript, wait for event to complete

I've got a problem near that one.
Somewhere I've got a binding over a file input :
var file;
function initLoadImg(){
$('#test').on('change', function() {
file = event.target.files;
// block 1
console.log("hello");
center.html('<span id="Tamb">25°C</span>');
over = true;
});
}
And i'm triggering it with another javascript function :
var over = false;
var center;
function loadImg(){
var elem = $('<div class="widget simpleimgchart center"><div class="matable"><div class="center"></div></div></div>');
center = elem.children().children();
$("#test").trigger('click');
passIfOver();
// block 2
console.log("bye");
return elem;
}
function passIfOver() {
if (over) {
return;
} else {
setTimeout(passIfOver(), 1000);
}
}
This way, I'm able to see the "hello" before the "bye" in the console.
However I don't really like this solution, (it's not clean) and user can have to wait up to 1s before getting any feedback.
Would there be another way to ensure that the return elem is executed after the end of the callback on click?
edit : My code doesn't even work, because of the setTimeout, I lose the restraint...
edit 2 : My goal is to execute the part code 1 before the part code 2. I don't want my function loadImg() to return before the code 1 has finished to execute.
I recommend you to look at PubSub pattern (http://davidwalsh.name/pubsub-javascript).
Just move the return inside the Trigger function:
var over = false;
function loadImg(){
var elem = $('<div class="widget simpleimgchart center"><div class="matable"><div class="center"></div></div></div>');
var center = elem.children().children();
$("#test").trigger('click', function(){
center.html('<span id="Tamb">25°C</span>');
return elem;
});
}
The second argument to .trigger is a callback function everything inside it will be executed After the trigger is completed.

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

$.getJSON request does not run but next line of code does

I have a $.getJSON request that does not run but the line of code right after the request does. If I remove all the code after the $.getJSON request the request will run. How do I get the request to run iterate over returned data then run code following the request.
var eventList = new Array();
$.getJSON('../index.php?/home/events', function(eventItems){
$.each(eventItems, function() {
var event = this;
var eventItem = new Array();
// format the date and append to span
eventItem[0] = formatMDYDate(formatTimeStamp(this.loc_datetime, false), 0);
// add shortdescription to div
eventItem[1] = this.shortdescription;
// check if longdescription exist
if (this.longdescription) {
// create new anchor element for "More Info" link on events
var link = $('<a></a>');
link.attr('href', '../index.php?/home/event_info');
link.addClass('popup');
link.html('More Info');
//link.bind('click', eventPopUp());
link.bind('click', function() {
var addressValue = event.id;
dialog = $('<div></div>').appendTo('body');
dialog.load('../index.php?/home/event_info',
{id: addressValue});
dialog.modal({
opacity: 80
});
return false;
});
eventItem[2] = link;
}
eventList.push(eventItem);
});
});
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
I have no idea what is causing this issue, please help!
Asynchronous means that when you call it the JS runtime will not wait for it to finish before executing next line of code. Typically you need to use call backs in this case.
It's something like:
var a="start";
setTimeout(function(){
a="done";
dosomethingWithA(a);
},1000);
if(a=="done"){}//doesn't matter, a is not "done"
function dosomethingWithA(a){
// a is "done" here
}
In your case the code should look something like:
var eventList = new Array();
$.getJSON('../index.php?/home/events', function(eventItems){
$.each(eventItems, function() {
var event = this;
var eventItem = new Array();
// format the date and append to span
eventItem[0] = formatMDYDate(formatTimeStamp(this.loc_datetime, false), 0);
// add shortdescription to div
eventItem[1] = this.shortdescription;
// check if longdescription exist
if (this.longdescription) {
// create new anchor element for "More Info" link on events
var link = $('<a></a>');
link.attr('href', '../index.php?/home/event_info');
link.addClass('popup');
link.html('More Info');
//link.bind('click', eventPopUp());
link.bind('click', function() {
var addressValue = event.id;
dialog = $('<div></div>').appendTo('body');
dialog.load('../index.php?/home/event_info',
{id: addressValue});
dialog.modal({
opacity: 80
});
return false;
});
eventItem[2] = link;
}
eventList.push(eventItem);
});
processEventList();
});
function processEventList(){
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
}
try
var eventList = new Array();
$.getJSON('../index.php?/home/events', function (eventItems) {
$.each(eventItems, function () {
//....
eventList.push(eventItem);
});
// removing the following lines of code will let the .getJSON request run
if (eventList.length > 0) {
write_Events(eventList);
}
});
Alternatively, you can use PubSub with jquery technique
var eventList = new Array();
$.getJSON('../index.php?/home/events', function (eventItems) {
$.each(eventItems, function () {
//....
eventList.push(eventItem);
});
//publisher
$(document).trigger('testEvent', eventList);
});
//subscriber
$(document).bind("testEvent", function (e, eventList) {
if (eventList.length > 0) {
write_Events(eventList);
}
});
For more detials http://www.codeproject.com/Articles/292151/PubSub-with-JQuery-Events
happy coding.. :)
$.getJSON is an asynchronous call. The callback will not execute until after the current function has executed completely. The code after the call will always run BEFORE the getJSON callback runs.
Its possible the write_Events function is throwing an error and stopping execution, which is why the callback is never running. Or it is actually running but you're not seeing evidence of it for whatever reason called by the extra code.
javascript code never wait for the response from the server and we need to stop the processing of javascript until we get the response from the server.
we can do this by using jquery.Deferred
You can also visit this tutorial.

Categories