javascript - array is not working in a function which is inside for loop of jquery -
i stuck @ point,its worpress mediauploader. want upload images, 1 function 1 image have several upload buttons unique id want 1 function thats why created loop, on click of each button media uploader open there problem saving selected image, not getting image url in value. pls new jquery , javascript. tried various methods 1 of them screenshot of thing want->here
jquery(document).ready(function($){ var b = ["#upload-button-1", "#upload-button-2", "#upload-button-3","#upload-button-4","#upload-button-5","#upload-button-6","#upload-button-7","#upload-button-8"]; var d =[".procircle-1", ".procircle-2",".procircle-3",".procircle-4",".procircle-5",".procircle-6",".procircle-7",".procircle-8"]; var j; var c = ["#grid-image-1", "#grid-image-2", "#grid-image-3","#grid-image-4","#grid-image-5","#grid-image-6","#grid-image-7","#grid-image-8"]; var i; for(i=0; i<=b.length; i++) { for(j=0;j<=c.length;j++){ $(b[i]).on('click',function(e){ e.preventdefault(); if( mediauploader ){ mediauploader.open(); return; } mediauploader = wp.media.frames.file_frame= wp.media({ title:'choose picture procedure ', button:{ text:'choose picture' }, multiple:false }); mediauploader.on('select',function(){ attachment= mediauploader.state().get('selection').first().tojson(); $(c[j]).val(attachment.url); $('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'}); }); mediauploader.open(); }); } } });
i suggest doing following (if must keep ids etc):
$(document).on('click', '#upload-button-1, #upload-button-2, #upload-button-3, #upload-button-4, #upload-button-5, #upload-button-6, #upload-button-7, #upload-button-8', function(e) { var match = e.target.id.match(/(\d+)/g); e.preventdefault(); if(mediauploader) { mediauploader.open(); return; } mediauploader = wp.media.frames.file_frame = wp.media({ title:'choose picture procedure ', button:{ text:'choose picture' }, multiple:false }); mediauploader.on('select', function(){ var attachment = mediauploader.state().get('selection').first().tojson(); var id = '#grid-image-' + match[1]; $(id).val(attachment.url); $('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'}); }); mediauploader.open(); });
this removes loop , delegates handler create 1 click handler rather 1 per loop iteration currently, , creates single mediauploader select handler. finally, match corresponding input event target performed click. should work, although might need play around bit, , refactored nicer. hope helps.
Comments
Post a Comment