It does not work "onclick" with attr () from JQuery - javascript

I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.

Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});

Do you write
$(Document)
Instead of $(document) with small letter "d".

Related

How can I wait until all my images are loaded before adding them to html?

I am trying to get multiple images from an ajax source and load the on the page when they have all finished loading. The issue I was having that has caused me to try to find a solution was that some of the images weren't loading even though those images existed on the server.
I have tried to add code that now adds the image to an array
design_images.push({cid:designImg});
... and then when all the images have loaded will add that to the page, but I can't get that to work.
var counter = 0;
$(design_images).load(function() { // many or just one image(w) inside body or any other container
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
Nothing is outputted from the .each
This is the output of the array design_images
The value of design_images.length is 0 though.
Here is the complete function:
function matte_design_change_design_type(element)
{
var element_value = null;
var mattes_selected_type = get_mattes_selected_type();
matte_design_widths[mattes_selected_type] = [];
var mattes_selected_design = get_mattes_selected_design();
var count_matte_designs = 0;
var found = false;
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: SITE_URL + "/system/components/xml/" + mattes_selected_type,
dataType: 'xml',
success: function(xml)
{
var output = [];
var design_images = [];
$('component', xml).each(function(i, el)
{
matte_design_widths[mattes_selected_type][i] = 0;
count_matte_designs++;
var thumb = $("thumb", this).text(),
cid = $("cid", this).first().text(),
name = $("name", this).first().text().replace("Collage - ", ""),
alt = name,
description = $("description", this).first().text(),
if (parseInt(cid, 10) === mattes_selected_design)
{
found = true;
$("#matte_design_name").html(name);
$("#matte_design_description").html(description);
}
var designImg = new Image();
designImg.id = 'cid_' + cid;
designImg.alt = alt;
designImg.onclick = function() {
matte_design_change(cid, mattes_selected_type);
};
designImg.onload = function() {
output.push('<span class="matte_design_image_name" id="design_' + cid + '"><img id="cid_' + cid + '" />');
output.push('<br /><span class="matte_design_name" id="matte_design_name_' + mattes_selected_type + '_' + i + '">' + name + '</span></span>');
matte_design_increase_width(mattes_selected_type, this.width, i);
$('#matte_designs_strip_wrapper').html(output.join(''));
};
designImg.src = 'https://example.com/system/components/compimg/' + thumb + '/flashthumb';
});
var counter = 0;
var size = $('img').length;
$(design_images).load(function() {
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
}
});
});
}
I have tried waitForImages and imagesLoaded but I couldn't get them to work for me, but I'm not opposed to using either one.
Hide all images by default using CSS
img{
display: none;
}
Use Jquery to check if all loaded, then display images
JQuery
$(window).load(function(){
$('img').fadeIn(800); //or $('img').show('slow');
});

Replace var with some new var jquery

I have code to find something from database and output it back if it exists.
Now when I output it back I need to make on click one of those outputs replace that output as var in some other var.
$(document).ready(function() {
$('#display').hide();
$("#leavepost").keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 35) {
$('#display').show();
$('#leavepost').on('keyup', function() {
var matches = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig)[0];
var name = matches;
$.ajax({
type: "POST",
url: "d/sul.php",
data: {
su: name
},
success: function(sss) {
$('#display').html(sss);
$(".adduser").click(function() {
var username = $(this).text();
var a = username;
var username2 = $(this).attr('id');
var E = "<a class='red' contenteditable='false' href='#' >" + a + "</a>";
var content = name.replace(name, E);
$("#leavepost").html(content);
$("#display").hide();
$("#leavepost").focus();
});
}
});
}).keyup();
}
});
});
When I click on class div hides but before that nothings happend... I need to replace #word from var name witdh var E.
Thanks
Your problem is most likely because you used .html() in on a <textarea> as stated in the discussion.
https://jsfiddle.net/q9gwdLj5/
$(function(){
$("#choices li").click(function(){
var name = $(this).text();
$("#ta").val($("#ta").val().replace("#thisperson", name));
})
})
Changing the .html() bit with .val() will fix the problem.

jquery address plugin issue

I’m using jquery address plugin , I have implemented the plugin on a listing page , when I click on one of the links , the function will pull the data using ajax and get the content and overwrite the current list html , this page has ‘back’ button , I use window.history.back() to go back to the listing page , this work fine until this point , but after that when I click again on one of the links again , the jq address behavior is lost .
the open_ajax function used to pull the data and inserted in paginatedContent html div
$(document).ready(function(){
refreshjQAddress();
});
function refreshjQAddress(){
mainPath = "";
if($('.jqaddress').length > 0){
$.address.init(function(event) {
$('.jqaddress').address(function() {
return $(this).attr('href');
});
}).internalChange('change', function(event) {
path = event.value;
var ran=Math.random();
urlPath = path;
console.log(urlPath);
alert(urlPath);
open_ajax(urlPath);
mainPath = urlPath;
}).externalChange(function(event) {
var windowLoc = window.location+"";
hashIndex = windowLoc.indexOf("#");
if(hashIndex > 0){
newLoc = windowLoc.substring(hashIndex+1);
mainLoc = windowLoc.substring(0,hashIndex);
if(mainLoc.indexOf("http://") > -1){
mainLoc = mainLoc.replace("http://","");
indexOf = mainLoc.indexOf("/");
mainLoc = mainLoc.substring(indexOf);
}
mainPath = mainLoc;
windowLoc = newLoc;
}
if(mainPath == ""){
mainPath = windowLoc;
}
if(windowLoc != mainPath){
var ran=Math.random();
open_ajax(windowLoc);
}
}).history(true);
}
}
var oldData;
function open_ajax(path){
var ran=Math.random();
if(path.indexOf("?") > 0){
urlPath=path+'&'+ran;
}else{
urlPath=path+'?'+ran;
}
oldData = $('#paginatedContent').html();
$.ajax({
url: path,
async: false,
beforeSend:function(data){
$('#paginatedContent').html("<div class='loaderDiv'><img src='/img/ajax-loader.gif' alt='' /></div>");
},
success: function(data) {
$('#paginatedContent').html("<div class='ajaxDataDiv' style='display:block'>"+data+"</div>");
if($("#hidden_meta_title").length > 0){
document.title = $("#hidden_meta_title").html();
}
$(".relatedBannersAlbums").show();
}
});
}
function back_btn(){
window.history.back();
}

Call function with argument from dynamically create link

I'm trying to create a grid of divs based on JSON that is returned from my server. When I iterate the objects, I create it like this
getApps(function(data){
var displayMode = "<? echo $_GET['displayMode']; ?>";
var appsDisplayedCounter = 0;
for (var i = 0; i < data.length; i++)
{
var app = data[i];
// check if we're interested in this app
var shouldDisplay = (displayMode == 'hired' && app.hired == 1) || (displayMode == 'self' && app.hired == 0) || !displayMode;
if (shouldDisplay)
{
var innerContent;
var content = '<div class="AppContainer">';
if (appsDisplayedCounter % 2 == 0)
{
innerContent = '<img class="SquareImage" src="'+app.imagePath+'"/>\
<div class="AppContainerName AppContainerBottomSegment">'+app.name+'</div>';
}
else
{
innerContent = '<div class="AppContainerName">'+app.name+'</div>\
<img class="SquareImage AppContainerBottomSegment" src="'+app.imagePath+'"/>';
}
content = content + innerContent + '</div>';
// nest the content in a link
content = '' + content + '';
$(".MainContentContainer").append(content);
// link handler
//$('#'+app.name).click(function(){showDetailView(app.name); return false});
// increment counter
appsDisplayedCounter++;
}
}
});
function showDetailView(app)
{
alert(app);
}
function getApps(completion)
{
$.ajax({
url: '/Apps.php',
success: function(data)
{
var appsJson = data['apps'];
completion(appsJson);
},
async: false
});
}
My issue is passing the app object into my function. Clicking the div does nothing.
-- EDIT --
When I inspect the tag after it was created, it looks like this
<a id="AppName" href="javascript:showDetailView([object Object])">
I set a breakpoint in showDetailView(app) which is never called when I click this link.
You are getting [object Object] because you are referencing it as a string, but it's not a string.
If you are trying to pass the entire object into the function, then you should use JSON.Stringify()
content = '<a href="javascript:showDetailView('+ JSON.stringify(app) +')"
id="'+app.name+'">' + content + '</a>';
Then in your showDetailView function:
function showDetailView(app) {
var appJSON = JSON.parse(app);
alert(aJSON.name);
}
References
JSON Object Overview
JSON.stringify()
JSON.parse()

Triggering Prototype change event with jQuery

I don't have all that much experience with Prototype and I've been working with jQuery to get things working properly on our site found here. Today I've added a jQuery based script for session handling. The problem I'm having is that even though I've gotten so far today in terms of functionality, I can't seem to get the change event fired via jQuery.
I'm using the following code currently, but it isn't working properly (you can test it on the site.. as soon as you change the year using your mouse, the AJAX is triggered and a Make can be selected)...
var yearSelected = jQuery.jStorage.get("yearSelected");
console.log(yearSelected);
// Set the vars...
if ((jQuery("div.amfinder-horizontal td:nth-child(1) select").val() == "0")) {
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
jQuery("div.amfinder-horizontal td:nth-child(1) select").trigger('change');
console.log('Set the year!');
}
The following code is the Prototype script controlling this and I need to fire off the change event, and would love to do it via jQuery if at all possible.
var amFinder = new Class.create();
amFinder.prototype = {
initialize: function(containerId, ajaxUrl, loadingText, isNeedLast, autoSubmit)
{
this.containerId = containerId;
this.ajaxUrl = ajaxUrl;
this.autoSubmit = Number(autoSubmit);
this.loadingText = loadingText;
this.isNeedLast = Number(isNeedLast);
this.selects = new Array();
//possible bug if select order in the HTML will be different
$$('#' + this.containerId + ' select').each(function(select){
select.observe('change', this.onChange.bindAsEventListener(this));
this.selects[this.selects.length] = select;
}.bind(this));
},
onChange: function(event)
{
var select = Event.element(event);
var parentId = select.value;
var dropdownId = 0;
/* should load next element's options only if current is not the last one */
for (var i = 0; i < this.selects.length; i++){
if (this.selects[i].id == select.id && i != this.selects.length-1){
var selectToReload = this.selects[i + 1];
if (selectToReload){
dropdownId = selectToReload.id.substr(selectToReload.id.search('--') + 2);
}
break;
}
}
this.clearAllBelow(select);
if (0 != parentId && dropdownId){
var postData = 'dropdown_id=' + dropdownId + '&parent_id=' + parentId;
new Ajax.Request(this.ajaxUrl, {
method: 'post',
postBody : postData,
evalJSON : 'force',
onLoading: function(){
this.showLoading(selectToReload);
}.bind(this),
onSuccess: function(transport) {
if (transport.responseJSON){
this.clearSelectOptions(selectToReload);
var itemsFound = false;
transport.responseJSON.each(function(item){
itemsFound = true;
var option = document.createElement('option');
option.value = item.value;
option.text = item.label;
option.label = item.label;
$(selectToReload).appendChild(option);
});
if (itemsFound){
$(selectToReload).disabled = false;
}
}
}.bind(this)
});
}
},
isLast: function(select)
{
return (this.selects[this.selects.length-1].id == select.id);
},
isFirst: function(select)
{
return (this.selects[0].id == select.id);
},
clearSelectOptions: function(select)
{
$(select).descendants().each(function(option){
option.remove();
});
},
clearAllBelow: function(select)
{
var startClearing = false;
for (var i = 0; i < this.selects.length; i++){
if (startClearing){
this.clearSelectOptions(this.selects[i]);
$(this.selects[i]).disabled = true;
}
if (this.selects[i].id == select.id){
startClearing = true;
}
}
var type = (((this.isLast(select) && !this.isNeedLast) && select.value > 0) || ((this.isNeedLast) && ((select.value > 0) || (!this.isFirst(select))))) ? 'block' : 'none';
if ('block' == type && this.autoSubmit && this.isLast(select))
{
$$('#' + this.containerId + ' .amfinder-buttons button')[0].form.submit();
} else {
$$('#' + this.containerId + ' .amfinder-buttons')[0].style.display = type;
}
},
showLoading: function(selectToReload)
{
var option = document.createElement('option');
option.value = 0;
option.text = this.loadingText;
option.label = this.loadingText;
$(selectToReload).appendChild(option);
},
};
I had the same problem. Here is solution. When you create : amfinder-horizontal the html goes something like this
<div class="amfinder-horizontal" id="amfinder_5333ffb212b09Container">
...
</div>
Look at id element : amfinder_5333ffb212b09 Container, bold part is also the name of variable that is amfinder object (created from prototype). It's a random name. This is from the extension source :
<?php $finderId = 'amfinder_' . uniqid(); ?>
...
<script type="text/javascript">
var <?php echo $finderId ?> = new amFinder(
'<?php echo $finderId ?>Container',
'<?php echo $this->getAjaxUrl() ?>',
'<?php echo $this->__('Loading...')?>',
'<?php echo Mage::getStoreConfig('amfinder/general/partial_search')?>',
<?php echo intval(Mage::getStoreConfig('amfinder/general/auto_submit')) ?>
);
</script>
So on every page refresh there is different name. var <?php echo $finderId ?>
Steps :
// Find the name for amfinder object.
var objName = jQuery("div.amfinder-horizontal").attr('id').replace('Container','');
// set Value to that select - copied from your code
jQuery("div.amfinder-horizontal td:nth-child(1) select option").each(function() { this.selected = (this.text == "2003"); });
// call the change event of that object
var targetObj = {
target : jQuery("div.amfinder-horizontal td:nth-child(1) select")[0]
};
window[objName].onChange(targetObj);

Categories