Search Results

Search found 291 results on 12 pages for 'appendto'.

Page 1/12 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Elements added with appendTo() not immediately available

    - by Zip Gun Jim
    I'm having a problem with elements added with appendTo() not being immediately available in the DOM. First, I'm reading some data from a JSON file and then appending some html to a div. jsonUrl = "js/performers.json"; $.getJSON(jsonUrl, function(json) { $.each(json.performers, function(i, performer) { var html = '<div class="performer_mini">'; html += '<img src="' + performer.thumbnail + '" alt="' + performer.name + '" /><br />'; html += performer.name + '<br /></div>'; $(html).appendTo("div#performer_spotlight"); }); }); Then I'm calling a random shuffler plugin to show one of the added divs at a time. $("#performer_spotlight").randomShuffler(".performer_mini", 3000, 3000, 9000); The random shuffler does the following: (function($) { $.fn.randomShuffler = function(shuffledElements, fadeInTime, fadeOutTime, timeout) { fadeInTime = fadeInTime || 3000; fadeOutTime = fadeOutTime || 3000; timeout = timeout || 9000; $(shuffledElements).hide(); var $old_element; var $new_element; var old_index = 0; var new_index = 0; function shuffleElement() { $old_element = $new_element; old_index = new_index; while ($(shuffledElements).length > 0 && old_index == new_index) { // don't display the same element twice in a row new_index = Math.floor(Math.random()*$(shuffledElements).length); } $new_element = $(shuffledElements + ":eq(" + new_index + ")"); if ($old_element != undefined) { $old_element.fadeOut(fadeOutTime, function() { $new_element.fadeIn(fadeInTime); }); } else { $new_element.fadeIn(fadeInTime); } setTimeout(shuffleElement, timeout); } $(this).show(); shuffleElement(); } })(jQuery); The first time the shuffleElement() function is called $(shuffledElements).length equals 0, so no element is displayed. On the next call to shuffleElement(), the elements added with appendTo() are available and one is selected at random as expected. Everything works correctly after that. Is there some way to refresh the DOM or make these elements available to jQuery immediately after I add them with appendTo()? Any other suggestions for how to accomplish this?

    Read the article

  • jQuery: appendTo parent

    - by Kenneth B
    Hi guys I can't seem to get the appendTo to work. What do I do wrong? $('div:nth-child(2n) img').appendTo(parent); Current markup: <div class="container"> <img src="123.jpg" /> <p>Hey</p> </div> <div class="container"> <img src="123.jpg" /> <p>Hey</p> </div> I want this output: <div class="container"> <p>Hey</p> <img src="123.jpg" /> </div> <div class="container"> <p>Hey</p> <img src="123.jpg" /> </div> Please help me guys... I'm tearing my hair of every minute.. :-S

    Read the article

  • How can i use appendTo and insertBefore properly

    - by Opoe
    hi all! With the append button i add elements to the same class. I want the append button and delete button beneath the appended elements, but when i use insertBefore, the Toggle function only toggles the buttons visibility. You can check out what i mean here; click add a box and start appending http://www.jsfiddle.net/myd3k/ replace appendTo with inserBefore and toggle the visibility. Thanks in advance

    Read the article

  • jquery appendTo form

    - by user313271
    jquery $(function(){ $('#4').click(function() { $('<input name="if4" type="text" value="other price>"').appendTo('form'); }); }); html <form> < input name="name" type="text" value="Enter your name" /><br /> < input name="contacts" type="text" value="Contact info" /><br /> < select name="services"> < option value="1">1</option> < option value="2">2</option> < option value="3">3</option> < option id="4" value="Other">4</option> < /select><br /> < textarea name="description">Description</textarea><br /> < /form> What i want to do: When i press on option value nr 4, there appears is new input field, this thing works fine. But how can I to change order where input field gonna appear, because now it appears after textfield, how can i put it after ? Thank you

    Read the article

  • appendTo() inside $.each in jquery seems to cause flicker....

    - by Pandiya Chendur
    appendTo() causes flicker when it is inside $.each.... $.each(jsob.Table, function(i, employee) { $('<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>').appendTo('#ResultsDiv'); }); Right now i am appending every new div to #ResultsDiv inside$.each is it good/bad to do so... If it is bad What can be done to make my divs appendTo() after the loop so that i it wont flicker.... EDIT:(based on answer) var divs = ''; $.each(jsob.Table, function(i, employee) { divs += '<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>'; }); $("#ResultsDiv").append(divs); But that too doesn't stop the flicker...

    Read the article

  • AppendTo does not work as desired

    - by Gokul
    When I say, msg.appendTo(ele.parent().next()), the msg successfully gets appended to a <p> with class=foo How can I specify it explicitly in the statement? I tried msg.appendTo(ele.parent().next().find('.foo')); but it doesn't work

    Read the article

  • jQuery appendTo (switching back and forth)

    - by Starboy
    So what I'm trying to accomplish is a simple appendTo a certain element. The issue I'm having is after execute is run, it appends to the location but then proceed to go back to the ul it resides in. <script type="text/javascript"> function execute() { $('#desCopy').appendTo('#description') $('#imgPlace').appendTo('#IMGbox') } </script> <div id="content" style="background:#000; width:989px;"> <div style="float:left; left:18px; margin:0; width:337px; position:relative; padding:15px 0 0 0; color:#FFF;"> <div id="description"> </div> </div> <div id="IMGbox" style="float:left; position:relative; display:block; background:#F00; width:652px; height:258px; background:#0FF; overflow:hidden;"> </div> <div style="float:right; background:#CCC; height:25px; width:652px;"> <ul> <li><a href="" onclick="execute()">Slide 1</a> <ul style=""> <li><span id="desCopy">Test description, Test description</span></li> <li><img src="images/test.jpg" id="imgPlace"></li> </ul> </li> </ul> </div> </div>

    Read the article

  • AppendTo, does it change the DOM?

    - by JD
    Hi, I have two list boxes and some JQuery function that does the following: $(document).ready(function () { //If you want to move selected item from fromListBox to toListBox $("#AddButton").click(function () { $("#fromListBox option:selected").appendTo("#toListBox"); }); }); I have a button that when clicked moves items from one list to another. This works, however when I do "View Page Source" in chrome, the list contains the original list and not the newly added items. I expected appendTo to change the DOM but clearly this is not what is happening. Why is this? JD

    Read the article

  • Appending html code to a section inside a dialog window isn't working in IE6

    - by user338413
    I'm using jQuery's validation on a form. When the form is validated, I'm using a submitHandler to fill a dialog with data from the form then I open the dialog to display it. Works great except for in IE6. Nothing displays. I've tried initializing the dialog before and after running the validation code but neither makes a difference. Here's the validation code: $("#acct").validate({ ... submitHandler: function() { fillVerificationDialog(); $("#verification_dialog").dialog('open'); return false; } }); Here's the fillVerificationDialog: function fillVerificationDialog() { $("#dialog-data").empty(); $("<span class='label'>").text("First Name: ").appendTo("#dialog-data"); $("<span class='value'>").text($("#firstname").val()).appendTo("#dialog-data"); $("<br/>").appendTo("#dialog-data"); ... }

    Read the article

  • jQuery animate() and appendTo() problem

    - by Devyn
    Hi! I'm doing a chess game. In there, I want to move an element with effect and then append it to new div. Following is my code. //--> #p70 is just ablove #p80 //--> each square is 64px $('#p80').animate({bottom:'+=64px'},500); //--> move one square above $('#b70').append($('#p80')); //--> append the animated element to owner 'div' The problem is, it moves 2 square( equivalent to 128px) where I only did is 64px. Here is my page and if you click the white square just above the pawn, you'll see the problem. I've tried adding delay(1000) and even javascript setTimeout but nothing works :( Really appreciate your helps in advance!

    Read the article

  • jQuery, html5, append()/appendTo() and IE

    - by karbassi
    How to replicate: Create an html5 page. Make sure you have the script from remysharp.com/2009/01/07/html5-enabling-script/ added so that IE will notice the tags. Create an hardcoded <section id='anything'></section> tag. Using jQuery 1.3.2, append another section tag: $('#anything').append('<section id="whatever"></section>'); So far, everything works in all the browsers. Repeat the previous step. $('#whatever').append('<section id="fail"></section>'); This is where IE6/7 fails. Firefox/Safari will continue working. Error This is the error displayed. Thoughts It could be that IE6/7 can't handle the HTML5 section tag. I say this because when I change step 4 from <section> to <div>, IE6/7 will start working. If I use document.createElement() and create my new element, it works, but it seems like jQuery's append() has a problem with html5 elements.

    Read the article

  • Use of clone() and appendTo() with draggable - unexpected results with dragging

    - by Matt Gutting
    I'm constructing a UI for a doctor scheduling app. We have several doctors, each of whom can go in one of several locations on a scheduled day (M - F). I have the main day/location grid (table) in the center of the screen. At the left is a table for the doctor names. On loading, each table cell contains a span (outlined) with the doctor name. The doctor name can go in one slot for each day. I didn't want to just put 5 copies of the doctor name, because the doctor might not be available all 5 days of the week. The idea was: Drag the span and drop into the calendar table. On the drag "start" event, clone the span and append it to the table cell. Now there is another span ready to be dropped into the calendar table. One line of code does the work: $(ui.helper).clone(true).prependTo(ui.helper.parent()); This works. But when I move the cloned span, the original one moves in sync - preserving the spatial relationships as I move the clone around (no doubt there's a "position:relative;left=XX;top=YY" inserted somewhere). I'm sure there's a way to do what I'm thinking of, while keeping the two spans independent. But I'm not thinking of one. Does anyone have an idea? Thanks! Matt I posted this identical question to the jQuery forum as well.

    Read the article

  • jquery how to make insertBefore work only once, on first click?

    - by user313271
    jquery $(function(){ $('#4').click(function() { $('<input name="if4" type="text" value="other price>"').insertBefore('form textarea'); }); }); html <form> < input name="name" type="text" value="Enter your name" /><br /> < input name="contacts" type="text" value="Contact info" /><br /> < select name="services"> < option value="1">1</option> < option value="2">2</option> < option value="3">3</option> < option id="4" value="Other">4</option> < /select><br /> < textarea name="description">Description</textarea><br /> < /form> And one more question about it, when i press on option number 4 two time,there appears 2 new fields, is there any way how to fix it, that new field appear only 1 time, after first click ?

    Read the article

  • jQuery append div to a specific

    - by ip
    Hi How do I append a element a specific index of the children elements using jQuery append e.g. if I have: <div class=".container"> <div class="item"><div> <div class="item"><div> <div class="item"><div> <div class="item"><div> </div> and I want to append another item between the second and third item?

    Read the article

  • Cannot see the variable In my own JQuery plugin's function.

    - by qinHaiXiang
    I am writing one of my own JQuery plugin. And I got some strange which make me confused. I am using JQuery UI datepicker with my plugin. ;(function($){ var newMW = 1, mwZIndex = 0; // IgtoMW contructor Igtomw = function(elem , options){ var activePanel, lastPanel, daysWithRecords, sliding; // used to check the animation below is executed to the end. // used to access the plugin's default configuration this.opts = $.extend({}, $.fn.igtomw.defaults, options); // intial the model window this.intialMW(); }; $.extend(Igtomw.prototype, { // intial model window intialMW : function(){ this.sliding = false; //this.daysWithRecords = []; this.igtoMW = $('<div />',{'id':'igto'+newMW,'class':'igtoMW',}) .css({'z-index':mwZIndex}) // make it in front of all exist model window; .appendTo('body') .draggable({ containment: 'parent' , handle: '.dragHandle' , distance: 5 }); //var igtoWrapper = igtoMW.append($('<div />',{'class':'igtoWrapper'})); this.igtoWrapper = $('<div />',{'class':'igtoWrapper'}).appendTo(this.igtoMW); this.igtoOpacityBody = $('<div />',{'class':'igtoOpacityBody'}).appendTo(this.igtoMW); //var igtoHeaderInfo = igtoWrapper.append($('<div />',{'class':'igtoHeaderInfo dragHandle'})); this.igtoHeaderInfo = $('<div />',{'class':'igtoHeaderInfo dragHandle'}) .appendTo(this.igtoWrapper); this.igtoQuickNavigation = $('<div />',{'class':'igtoQuickNavigation'}) .css({'color':'#fff'}) .appendTo(this.igtoWrapper); this.igtoContentSlider = $('<div />',{'class':'igtoContentSlider'}) .appendTo(this.igtoWrapper); this.igtoQuickMenu = $('<div />',{'class':'igtoQuickMenu'}) .appendTo(this.igtoWrapper); this.igtoFooter = $('<div />',{'class':'igtoFooter dragHandle'}) .appendTo(this.igtoWrapper); // append to igtoHeaderInfo this.headTitle = this.igtoHeaderInfo.append($('<div />',{'class':'headTitle'})); // append to igtoQuickNavigation this.igQuickNav = $('<div />', {'class':'igQuickNav'}) .html('??') .appendTo(this.igtoQuickNavigation); // append to igtoContentSlider this.igInnerPanelTopMenu = $('<div />',{'class':'igInnerPanelTopMenu'}) .appendTo(this.igtoContentSlider); this.igInnerPanelTopMenu.append('<div class="igInnerPanelButtonPreWrapper"><a href="" class="igInnerPanelButton Pre" action="" style="background-image:url(images/igto/igInnerPanelTopMenu.bt.bg.png);"></a></div>'); this.igInnerPanelTopMenu.append('<div class="igInnerPanelSearch"><input type="text" name="igInnerSearch" /><a href="" class="igInnerSearch">??</a></div>' ); this.igInnerPanelTopMenu.append('<div class="igInnerPanelButtonNextWrapper"><a href="" class="igInnerPanelButton Next" action="sm" style="background-image:url(images/igto/igInnerPanelTopMenu.bt.bg.png); background-position:-272px"></a></div>' ); this.igInnerPanelBottomMenu = $('<div />',{'class':'igInnerPanelBottomMenu'}) .appendTo(this.igtoContentSlider); this.icWrapper = $('<div />',{'class':'icWrapper','id':'igto'+newMW+'Panel'}) .appendTo(this.igtoContentSlider); this.icWrapperCotentPre = $('<div class="slider pre"></div>').appendTo(this.icWrapper); this.icWrapperCotentShow = $('<div class="slider firstShow "></div>').appendTo(this.icWrapper); this.icWrapperCotentnext = $('<div class="slider next"></div>').appendTo(this.icWrapper); this.initialPanel(); this.initialQuickMenus(); console.log(this.leftPad(9)); newMW++; mwZIndex++; this.igtoMW.bind('mousedown',function(){ var $this = $(this); //alert($this.css('z-index') + ' '+mwZIndex); if( parseInt($this.css('z-index')) === (mwZIndex-1) ) return; $this.css({'z-index':mwZIndex}); mwZIndex++; //alert(mwZIndex); }); }, initialPanel : function(){ this.defaultPanelNum = this.opts.initialPanel; this.activePanel = this.defaultPanelNum; this.lastPanel = this.defaultPanelNum; this.defaultPanel = this.loadPanelContents(this.defaultPanelNum); $(this.defaultPanel).appendTo(this.icWrapperCotentShow); }, initialQuickMenus : function(){ // store the current element var obj = this; var defaultQM = this.opts.initialQuickMenu; var strMenu = ''; var marginFirstEle = '8'; $.each(defaultQM,function(key,value){ //alert(key+':'+value); if(marginFirstEle === '8'){ strMenu += '<a href="" class="btPanel" panel="'+key+'" style="margin-left: 8px;" >'+value+'</a>'; marginFirstEle = '4'; } else{ strMenu += '<a href="" class="btPanel" panel="'+key+'" style="margin-left: 4px;" >'+value+'</a>'; } }); // append to igtoQuickMenu this.igtoQMenu = $(strMenu).appendTo(this.igtoQuickMenu); this.igtoQMenu.bind('click',function(event){ event.preventDefault(); var element = $(this); if(element.is('.active')){ return; } else{ $(obj.igtoQMenu).removeClass('active'); element.addClass('active'); } var d = new Date(); var year = d.getFullYear(); var month = obj.leftPad( d.getMonth() ); var inst = null; if( obj.sliding === false){ console.log(obj.lastPanel); var currentPanelNum = parseInt(element.attr('panel')); obj.checkAvailability(); obj.getDays(year,month,inst,currentPanelNum); obj.slidePanel(currentPanelNum); obj.activePanel = currentPanelNum; console.log(obj.activePanel); obj.lastPanel = obj.activePanel; obj.icWrapper.find('input').val(obj.activePanel); } }); }, initialLoginPanel : function(){ var obj = this; this.igPanelLogin = $('<div />',{'class':"igPanelLogin"}); this.igEnterName = $('<div />',{'class':"igEnterName"}).appendTo(this.igPanelLogin); this.igInput = $('<input type="text" name="name" value="???" />').appendTo(this.igEnterName); this.igtoLoginBtWrap = $('<div />',{'class':"igButtons"}).appendTo(this.igPanelLogin); this.igtoLoginBt = $('<a href="" class="igtoLoginBt" action="OK" >??</a>\ <a href="" class="igtoLoginBt" action="CANCEL" >??</a>\ <a href="" class="igtoLoginBt" action="ADD" >????</a>').appendTo(this.igtoLoginBtWrap); this.igtoLoginBt.bind('click',function(event){ event.preventDefault(); var elem = $(this); var action = elem.attr('action'); var userName = obj.igInput.val(); obj.loadRootMenu(); }); return this.igPanelLogin; }, initialWatchHistory : function(){ var obj = this; // for thirt part plugin used if(this.sliding === false){ this.watchHistory = $('<div />',{'class':'igInnerPanelSlider'}).append($('<div />',{'class':'igInnerPanel_pre'}).addClass('igInnerPanel')) .append($('<div />',{'class':'igInnerPanel'}).datepicker({ dateFormat: 'yy-mm-dd',defaultDate: '2010-12-01' ,showWeek: true,firstDay: 1, //beforeShow:setDateStatistics(), onChangeMonthYear:function(year, month, inst) { var panelNum = 1; month = obj.leftPad(month); obj.getDays(year,month,inst,panelNum); } , beforeShowDay: obj.checkAvailability, onSelect: function(dateText, inst) { obj.checkAvailability(); } }).append($('<div />',{'class':'extraMenu'})) ) .append($('<div />',{'class':'igInnerPanel_next'}).addClass('igInnerPanel')); return this.watchHistory; } }, loadPanelContents : function(panelNum){ switch(panelNum){ case 1: alert('inside loadPanelContents') return this.initialWatchHistory(); break; case 2: return this.initialWatchHistory(); break; case 3: return this.initialWatchHistory(); break; case 4: return this.initialWatchHistory(); break; case 5: return this.initialLoginPanel(); break; } }, loadRootMenu : function(){ var obj = this; var mainMenuPanel = $('<div />',{'class':'igRootMenu'}); var currentMWId = this.igtoMW.attr('id'); this.activePanel = 0; $('#'+currentMWId+'Panel .pre'). queue(function(next){ $(this). html(mainMenuPanel). addClass('panelShow'). removeClass('pre'). attr('panelNum',0); next(); }). queue(function(next){ $('<div style="width:0;" class="slider pre"></div>'). prependTo('#'+currentMWId+'Panel').animate({width:348}, function(){ $('#'+currentMWId+'Panel .slider:last').remove() $('#'+currentMWId+'Panel .slider:last').replaceWith('<div class="slider next"></div>'); $('.btMenu').remove(); // remove bottom quick menu obj.sliding = false; $(this).removeAttr('style'); }); $('.igtoQuickMenu .active').removeClass('active'); next(); }); }, slidePanel : function(currentPanelNum){ var currentMWId = this.igtoMW.attr('id'); var obj = this; //alert(obj.loadPanelContents(currentPanelNum)); if( this.activePanel > currentPanelNum){ $('#'+currentMWId+'Panel .pre'). queue(function(next){ alert('inside slidePanel') //var initialDate = getPanelDateStatus(panelNum); //console.log('intial day in bigger panel '+initialDate) $(this). html(obj.loadPanelContents(currentPanelNum)). addClass('panelShow'). removeClass('pre'). attr('panelNum',currentPanelNum); $('#'+currentMWId+'Panel .next').remove(); next(); }). queue(function(next){ $('<div style="width:0;" class="slider pre"></div>'). prependTo('#'+currentMWId+'Panel').animate({width:348}, function(){ //$('#igto1Panel .slider:last').find(setPanel(currentPanelNum)).datepicker('destroy'); $('#'+currentMWId+'Panel .slider:last').empty().removeClass('panelShow').addClass('next').removeAttr('panelNum'); $('#'+currentMWId+'Panel .slider:last').replaceWith('<div class="slider next"></div>') obj.sliding = false;console.log('inuse inside animation: '+obj.sliding); $(this).removeAttr('style'); }); next(); }); } else{ ///// current panel num smaller than next $('#'+currentMWId+'Panel .next'). queue(function(next){ $(this). html(obj.loadPanelContents(currentPanelNum)). addClass('panelShow'). removeClass('next'). attr('panelNum',currentPanelNum); $('<div class="slider next">empty</div>').appendTo('#'+currentMWId+'Panel'); next(); }). queue(function(next){ $('#'+currentMWId+'Panel .pre').animate({width:0}, function(){ $(this).remove(); //$('#igto1Panel .slider:first').find(setPanel(currentPanelNum)).datepicker('destroy'); $('#'+currentMWId+'Panel .slider:first').empty().removeClass('panelShow').addClass('pre').removeAttr('panelNum').removeAttr('style'); $('#'+currentMWId+'Panel .slider:first').replaceWith('<div class="slider pre"></div>') obj.sliding = false; console.log('inuse inside animation: '+obj.sliding); }); next(); }); } }, getDays : function(year,month,inst,panelNum){ var obj = this; // depand on the mysql qurey condition var table_of_record = 'moviewh';//getTable(panelNum); var date_of_record = 'watching_date';//getTableDateCol(panelNum); var date_to_find = year+'-'+month; var node_of_xml_date_list = 'whDateRecords';//getXMLDateNode(panelNum); var user_id = '1';//getLoginUserId(); //var daysWithRecords = []; // empty array before asigning this.daysWithRecords.length = 0; $.ajax({ type: "GET", url: "include/get.date.list.process.php", data:({ table_of_record : table_of_record,date_of_record:date_of_record,date_to_find:date_to_find,user_id:user_id,node_of_xml_date_list:node_of_xml_date_list }), dataType: "json", cache: false, // force broser don't cache the xml file async: false, // using this option to prevent datepicker refresh ??NO success:function(data){ // had no date records if(data === null) return; obj.daysWithRecords = data; } }); //setPanelDateStatus(year,month,panelNum); console.log('call from getdays() ' + this.daysWithRecords); }, checkAvailability : function(availableDays) { // var i; var checkdate = $.datepicker.formatDate('yy-mm-dd', availableDays); //console.log( checkdate); // for(var i = 0; i < this.daysWithRecords.length; i++) { // // if(this.daysWithRecords[i] == checkdate){ // // return [true, "available"]; // } // } //console.log('inside check availablility '+ this.daysWithRecords); //return [true, "available"]; console.log(typeof this.daysWithRecords) for(i in this.daysWithRecords){ //if(this.daysWithRecords[i] == checkdate){ console.log(typeof this.daysWithRecords[i]); //return [true, "available"]; //} } return [true, "available"]; //return [false, ""]; }, leftPad : function(num) { return (num < 10) ? '0' + num : num; } }); $.fn.igtomw = function(options){ // Merge options passed in with global defaults var opt = $.extend({}, $.fn.igtomw.defaults , options); return this.each(function() { new Igtomw(this,opt); }); }; $.fn.igtomw.defaults = { // 0:mainMenu 1:whatchHistor 2:requestHistory 3:userManager // 4:shoppingCart 5:loginPanel initialPanel : 5, // default panel is LoginPanel initialQuickMenu : {'1':'whatchHIstory','2':'????','3':'????','4':'????'} // defalut quick menu }; })(jQuery); usage: $('.openMW').click(function(event){ event.preventDefault(); $('<div class="">').igtomw(); }) HTML code: <div id="taskBarAndStartMenu"> <div class="taskBarAndStartMenuM"> <a href="" class="openMW" >??IGTO</a> </div> <div class="taskBarAndStartMenuO"></div> </div> In my work flow: when I click the "whatchHistory" button, my plugin would load a panel with JQuery UI datepicker applied which days had been set to be availabled or not. I am using the function "getDays()" to get the available days list and stored the data inside daysWithRecords, and final the UI datepicker's function "beforeShowDay()" called the function "checkAvailability()" to set the days. the variable "daysWithRecords" was declared inside Igtomw = function(elem , options) and was initialized inside the function getDays() I am using the function "initialWatchHistory()" to initialization and render the JQuery UI datepicker in the web. My problem is the function "checkAvailability()" cannot see the variable "daysWithRecords".The firebug prompts me that "daysWithRecords" is "undefined". this is the first time I write my first plugin. So .... Thank you very much for any help!!

    Read the article

  • $('<style></style>').text('css').appendTo('head') does not work in IE?

    - by powerboy
    It works fine in Firefox and Chrome, but does not work in IE8. Here is the html structure: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { // this does not work in the stupid IE $('<style type="text/css"></style>').text('body {margin: 0;}').appendTo('head'); }); </script> </head> <body> </body> </html> And what' s the alternative to do this in IE?

    Read the article

  • jQuery Validation, multiple form ids for same function

    - by George
    Hi have two forms with the exact same validation rules, but different ids that I'd like to combine into just one function. How can I do that? var validator = $("#ValidateForm1").validate({ errorPlacement: function(error, element) { if ( element.is(":radio") ) error.appendTo( element.parent().next().next() ); else if ( element.is(":checkbox") ) error.appendTo ( element.next() ); else error.appendTo( element.parent().next() ); } }); var validator = $("#validateForm2").validate({ errorPlacement: function(error, element) { if ( element.is(":radio") ) error.appendTo( element.parent().next().next() ); else if ( element.is(":checkbox") ) error.appendTo ( element.next() ); else error.appendTo( element.parent().next() ); } });

    Read the article

  • An Introduction to jQuery Templates

    - by Stephen Walther
    The goal of this blog entry is to provide you with enough information to start working with jQuery Templates. jQuery Templates enable you to display and manipulate data in the browser. For example, you can use jQuery Templates to format and display a set of database records that you have retrieved with an Ajax call. jQuery Templates supports a number of powerful features such as template tags, template composition, and wrapped templates. I’ll concentrate on the features that I think that you will find most useful. In order to focus on the jQuery Templates feature itself, this blog entry is server technology agnostic. All the samples use HTML pages instead of ASP.NET pages. In a future blog entry, I’ll focus on using jQuery Templates with ASP.NET Web Forms and ASP.NET MVC (You can do some pretty powerful things when jQuery Templates are used on the client and ASP.NET is used on the server). Introduction to jQuery Templates The jQuery Templates plugin was developed by the Microsoft ASP.NET team in collaboration with the open-source jQuery team. While working at Microsoft, I wrote the original proposal for jQuery Templates, Dave Reed wrote the original code, and Boris Moore wrote the final code. The jQuery team – especially John Resig – was very involved in each step of the process. Both the jQuery community and ASP.NET communities were very active in providing feedback. jQuery Templates will be included in the jQuery core library (the jQuery.js library) when jQuery 1.5 is released. Until jQuery 1.5 is released, you can download the jQuery Templates plugin from the jQuery Source Code Repository or you can use jQuery Templates directly from the ASP.NET CDN. The documentation for jQuery Templates is already included with the official jQuery documentation at http://api.jQuery.com. The main entry for jQuery templates is located under the topic plugins/templates. A Basic Sample of jQuery Templates Let’s start with a really simple sample of using jQuery Templates. We’ll use the plugin to display a list of books stored in a JavaScript array. Here’s the complete code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html > <head> <title>Intro</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" }, ]; // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html> When you open this page in a browser, a list of books is displayed: There are several things going on in this page which require explanation. First, notice that the page uses both the jQuery 1.4.4 and jQuery Templates libraries. Both libraries are retrieved from the ASP.NET CDN: <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> You can use the ASP.NET CDN for free (even for production websites). You can learn more about the files included on the ASP.NET CDN by visiting the ASP.NET CDN documentation page. Second, you should notice that the actual template is included in a script tag with a special MIME type: <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> This template is displayed for each of the books rendered by the template. The template displays a book picture, title, and price. Notice that the SCRIPT tag which wraps the template has a MIME type of text/x-jQuery-tmpl. Why is the template wrapped in a SCRIPT tag and why the strange MIME type? When a browser encounters a SCRIPT tag with an unknown MIME type, it ignores the content of the tag. This is the behavior that you want with a template. You don’t want a browser to attempt to parse the contents of a template because this might cause side effects. For example, the template above includes an <img> tag with a src attribute that points at “BookPictures/${picture}”. You don’t want the browser to attempt to load an image at the URL “BookPictures/${picture}”. Instead, you want to prevent the browser from processing the IMG tag until the ${picture} expression is replaced by with the actual name of an image by the jQuery Templates plugin. If you are not worried about browser side-effects then you can wrap a template inside any HTML tag that you please. For example, the following DIV tag would also work with the jQuery Templates plugin: <div id="bookTemplate" style="display:none"> <div> <h2>${title}</h2> price: ${formatPrice(price)} </div> </div> Notice that the DIV tag includes a style=”display:none” attribute to prevent the template from being displayed until the template is parsed by the jQuery Templates plugin. Third, notice that the expression ${…} is used to display the value of a JavaScript expression within a template. For example, the expression ${title} is used to display the value of the book title property. You can use any JavaScript function that you please within the ${…} expression. For example, in the template above, the book price is formatted with the help of the custom JavaScript formatPrice() function which is defined lower in the page. Fourth, and finally, the template is rendered with the help of the tmpl() method. The following statement selects the bookTemplate and renders an array of books using the bookTemplate. The results are appended to a DIV element named bookContainer by using the standard jQuery appendTo() method. $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); Using Template Tags Within a template, you can use any of the following template tags. {{tmpl}} – Used for template composition. See the section below. {{wrap}} – Used for wrapped templates. See the section below. {{each}} – Used to iterate through a collection. {{if}} – Used to conditionally display template content. {{else}} – Used with {{if}} to conditionally display template content. {{html}} – Used to display the value of an HTML expression without encoding the value. Using ${…} or {{= }} performs HTML encoding automatically. {{= }}-- Used in exactly the same way as ${…}. {{! }} – Used for displaying comments. The contents of a {{!...}} tag are ignored. For example, imagine that you want to display a list of blog entries. Each blog entry could, possibly, have an associated list of categories. The following page illustrates how you can use the { if}} and {{each}} template tags to conditionally display categories for each blog entry:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>each</title> <link href="1_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="blogPostContainer"></div> <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> var blogPosts = [ { postTitle: "How to fix a sink plunger in 5 minutes", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.", categories: ["HowTo", "Sinks", "Plumbing"] }, { postTitle: "How to remove a broken lightbulb", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.", categories: ["HowTo", "Lightbulbs", "Electricity"] }, { postTitle: "New associate website", postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna." } ]; // Render the blog posts $("#blogPostTemplate").tmpl(blogPosts).appendTo("#blogPostContainer"); </script> </body> </html> When this page is opened in a web browser, the following list of blog posts and categories is displayed: Notice that the first and second blog entries have associated categories but the third blog entry does not. The third blog entry is “Uncategorized”. The template used to render the blog entries and categories looks like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script> Notice the special expression $value used within the {{each}} template tag. You can use $value to display the value of the current template item. In this case, $value is used to display the value of each category in the collection of categories. Template Composition When building a fancy page, you might want to build a template out of multiple templates. In other words, you might want to take advantage of template composition. For example, imagine that you want to display a list of products. Some of the products are being sold at their normal price and some of the products are on sale. In that case, you might want to use two different templates for displaying a product: a productTemplate and a productOnSaleTemplate. The following page illustrates how you can use the {{tmpl}} tag to build a template from multiple templates:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Composition</title> <link href="2_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContainer"> <h1>Products</h1> <div id="productListContainer"></div> <!-- Show list of products using composition --> <script id="productListTemplate" type="text/x-jQuery-tmpl"> <div> {{if onSale}} {{tmpl "#productOnSaleTemplate"}} {{else}} {{tmpl "#productTemplate"}} {{/if}} </div> </script> <!-- Show product --> <script id="productTemplate" type="text/x-jQuery-tmpl"> ${name} </script> <!-- Show product on sale --> <script id="productOnSaleTemplate" type="text/x-jQuery-tmpl"> <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" /> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> var products = [ { name: "Laptop", onSale: false }, { name: "Apples", onSale: true }, { name: "Comb", onSale: false } ]; $("#productListTemplate").tmpl(products).appendTo("#productListContainer"); </script> </div> </body> </html>   In the page above, the main template used to display the list of products looks like this: <script id="productListTemplate" type="text/x-jQuery-tmpl"> <div> {{if onSale}} {{tmpl "#productOnSaleTemplate"}} {{else}} {{tmpl "#productTemplate"}} {{/if}} </div> </script>   If a product is on sale then the product is displayed with the productOnSaleTemplate (which includes an on sale image): <script id="productOnSaleTemplate" type="text/x-jQuery-tmpl"> <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" /> </script>   Otherwise, the product is displayed with the normal productTemplate (which does not include the on sale image): <script id="productTemplate" type="text/x-jQuery-tmpl"> ${name} </script>   You can pass a parameter to the {{tmpl}} tag. The parameter becomes the data passed to the template rendered by the {{tmpl}} tag. For example, in the previous section, we used the {{each}} template tag to display a list of categories for each blog entry like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{each categories}} <i>${$value}</i> {{/each}} {{else}} Uncategorized {{/if}} </script>   Another way to create this template is to use template composition like this: <script id="blogPostTemplate" type="text/x-jQuery-tmpl"> <h1>${postTitle}</h1> <p> ${postEntry} </p> {{if categories}} Categories: {{tmpl(categories) "#categoryTemplate"}} {{else}} Uncategorized {{/if}} </script> <script id="categoryTemplate" type="text/x-jQuery-tmpl"> <i>${$data}</i> &nbsp; </script>   Using the {{each}} tag or {{tmpl}} tag is largely a matter of personal preference. Wrapped Templates The {{wrap}} template tag enables you to take a chunk of HTML and transform the HTML into another chunk of HTML (think easy XSLT). When you use the {{wrap}} tag, you work with two templates. The first template contains the HTML being transformed and the second template includes the filter expressions for transforming the HTML. For example, you can use the {{wrap}} template tag to transform a chunk of HTML into an interactive tab strip: When you click any of the tabs, you see the corresponding content. This tab strip was created with the following page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Wrapped Templates</title> <style type="text/css"> body { font-family: Arial; background-color:black; } .tabs div { display:inline-block; border-bottom: 1px solid black; padding:4px; background-color:gray; cursor:pointer; } .tabs div.tabState_true { background-color:white; border-bottom:1px solid white; } .tabBody { border-top:1px solid white; padding:10px; background-color:white; min-height:400px; width:400px; } </style> </head> <body> <div id="tabsView"></div> <script id="tabsContent" type="text/x-jquery-tmpl"> {{wrap "#tabsWrap"}} <h3>Tab 1</h3> <div> Content of tab 1. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 2</h3> <div> Content of tab 2. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 3</h3> <div> Content of tab 3. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> {{/wrap}} </script> <script id="tabsWrap" type="text/x-jquery-tmpl"> <div class="tabs"> {{each $item.html("h3", true)}} <div class="tabState_${$index === selectedTabIndex}"> ${$value} </div> {{/each}} </div> <div class="tabBody"> {{html $item.html("div")[selectedTabIndex]}} </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Global for tracking selected tab var selectedTabIndex = 0; // Render the tab strip $("#tabsContent").tmpl().appendTo("#tabsView"); // When a tab is clicked, update the tab strip $("#tabsView") .delegate(".tabState_false", "click", function () { var templateItem = $.tmplItem(this); selectedTabIndex = $(this).index(); templateItem.update(); }); </script> </body> </html>   The “source” for the tab strip is contained in the following template: <script id="tabsContent" type="text/x-jquery-tmpl"> {{wrap "#tabsWrap"}} <h3>Tab 1</h3> <div> Content of tab 1. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 2</h3> <div> Content of tab 2. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> <h3>Tab 3</h3> <div> Content of tab 3. Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. </div> {{/wrap}} </script>   The tab strip is created with a list of H3 elements (which represent each tab) and DIV elements (which represent the body of each tab). Notice that the HTML content is wrapped in the {{wrap}} template tag. This template tag points at the following tabsWrap template: <script id="tabsWrap" type="text/x-jquery-tmpl"> <div class="tabs"> {{each $item.html("h3", true)}} <div class="tabState_${$index === selectedTabIndex}"> ${$value} </div> {{/each}} </div> <div class="tabBody"> {{html $item.html("div")[selectedTabIndex]}} </div> </script> The tabs DIV contains all of the tabs. The {{each}} template tag is used to loop through each of the H3 elements from the source template and render a DIV tag that represents a particular tab. The template item html() method is used to filter content from the “source” HTML template. The html() method accepts a jQuery selector for its first parameter. The tabs are retrieved from the source template by using an h3 filter. The second parameter passed to the html() method – the textOnly parameter -- causes the filter to return the inner text of each h3 element. You can learn more about the html() method at the jQuery website (see the section on $item.html()). The tabBody DIV renders the body of the selected tab. Notice that the {{html}} template tag is used to display the tab body so that HTML content in the body won’t be HTML encoded. The html() method is used, once again, to grab all of the DIV elements from the source HTML template. The selectedTabIndex global variable is used to display the contents of the selected tab. Remote Templates A common feature request for jQuery templates is support for remote templates. Developers want to be able to separate templates into different files. Adding support for remote templates requires only a few lines of extra code (Dave Ward has a nice blog entry on this). For example, the following page uses a remote template from a file named BookTemplate.htm: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Remote Templates</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" }, ]; // Get the remote template $.get("BookTemplate.htm", null, function (bookTemplate) { // Render the books using the remote template $.tmpl(bookTemplate, books).appendTo("#bookContainer"); }); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   The remote template is retrieved (and rendered) with the following code: // Get the remote template $.get("BookTemplate.htm", null, function (bookTemplate) { // Render the books using the remote template $.tmpl(bookTemplate, books).appendTo("#bookContainer"); });   This code uses the standard jQuery $.get() method to get the BookTemplate.htm file from the server with an Ajax request. After the BookTemplate.htm file is successfully retrieved, the $.tmpl() method is used to render an array of books with the template. Here’s what the BookTemplate.htm file looks like: <div> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> Notice that the template in the BooksTemplate.htm file is not wrapped by a SCRIPT element. There is no need to wrap the template in this case because there is no possibility that the template will get interpreted before you want it to be interpreted. If you plan to use the bookTemplate multiple times – for example, you are paging or sorting the books -- then you should compile the template into a function and cache the compiled template function. For example, the following page can be used to page through a list of 100 products (using iPhone style More paging). <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Template Caching</title> <link href="6_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Products</h1> <div id="productContainer"></div> <button id="more">More</button> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Globals var pageIndex = 0; // Create an array of products var products = []; for (var i = 0; i < 100; i++) { products.push({ name: "Product " + (i + 1) }); } // Get the remote template $.get("ProductTemplate.htm", null, function (productTemplate) { // Compile and cache the template $.template("productTemplate", productTemplate); // Render the products renderProducts(0); }); $("#more").click(function () { pageIndex++; renderProducts(); }); function renderProducts() { // Get page of products var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5); // Used cached productTemplate to render products $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer"); } function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   The ProductTemplate is retrieved from an external file named ProductTemplate.htm. This template is retrieved only once. Furthermore, it is compiled and cached with the help of the $.template() method: // Get the remote template $.get("ProductTemplate.htm", null, function (productTemplate) { // Compile and cache the template $.template("productTemplate", productTemplate); // Render the products renderProducts(0); });   The $.template() method compiles the HTML representation of the template into a JavaScript function and caches the template function with the name productTemplate. The cached template can be used by calling the $.tmp() method. The productTemplate is used in the renderProducts() method: function renderProducts() { // Get page of products var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5); // Used cached productTemplate to render products $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer"); } In the code above, the first parameter passed to the $.tmpl() method is the name of a cached template. Working with Template Items In this final section, I want to devote some space to discussing Template Items. A new Template Item is created for each rendered instance of a template. For example, if you are displaying a list of 100 products with a template, then 100 Template Items are created. A Template Item has the following properties and methods: data – The data associated with the Template Instance. For example, a product. tmpl – The template associated with the Template Instance. parent – The parent template item if the template is nested. nodes – The HTML content of the template. calls – Used by {{wrap}} template tag. nest – Used by {{tmpl}} template tag. wrap – Used to imperatively enable wrapped templates. html – Used to filter content from a wrapped template. See the above section on wrapped templates. update – Used to re-render a template item. The last method – the update() method -- is especially interesting because it enables you to re-render a template item with new data or even a new template. For example, the following page displays a list of books. When you hover your mouse over any of the books, additional book details are displayed. In the following screenshot, details for ASP.NET Kick Start are displayed. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Template Item</title> <link href="0_Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="pageContent"> <h1>ASP.NET Bookstore</h1> <div id="bookContainer"></div> </div> <script id="bookTemplate" type="text/x-jQuery-tmpl"> <div class="bookItem"> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} </div> </script> <script id="bookDetailsTemplate" type="text/x-jQuery-tmpl"> <div class="bookItem"> <img src="BookPictures/${picture}" alt="" /> <h2>${title}</h2> price: ${formatPrice(price)} <p> ${description} </p> </div> </script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script> <script type="text/javascript"> // Create an array of books var books = [ { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg", description: "The most comprehensive book on Microsoft’s new ASP.NET 4.. " }, { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg", description: "Writing for professional programmers, Walther explains the crucial concepts that make the Model-View-Controller (MVC) development paradigm work…" }, { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg", description: "Visual Studio .NET is the premier development environment for creating .NET applications…." }, { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg", description: "ASP.NET MVC Unleashed for the iPhone…" }, ]; // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); // Get compiled details template var bookDetailsTemplate = $("#bookDetailsTemplate").template(); // Add hover handler $(".bookItem").mouseenter(function () { // Get template item associated with DIV var templateItem = $(this).tmplItem(); // Change template to compiled template templateItem.tmpl = bookDetailsTemplate; // Re-render template templateItem.update(); }); function formatPrice(price) { return "$" + price.toFixed(2); } </script> </body> </html>   There are two templates used to display a book: bookTemplate and bookDetailsTemplate. When you hover your mouse over a template item, the standard bookTemplate is swapped out for the bookDetailsTemplate. The bookDetailsTemplate displays a book description. The books are rendered with the bookTemplate with the following line of code: // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer");   The following code is used to swap the bookTemplate and the bookDetailsTemplate to show details for a book: // Get compiled details template var bookDetailsTemplate = $("#bookDetailsTemplate").template(); // Add hover handler $(".bookItem").mouseenter(function () { // Get template item associated with DIV var templateItem = $(this).tmplItem(); // Change template to compiled template templateItem.tmpl = bookDetailsTemplate; // Re-render template templateItem.update(); });   When you hover your mouse over a DIV element rendered by the bookTemplate, the mouseenter handler executes. First, this handler retrieves the Template Item associated with the DIV element by calling the tmplItem() method. The tmplItem() method returns a Template Item. Next, a new template is assigned to the Template Item. Notice that a compiled version of the bookDetailsTemplate is assigned to the Template Item’s tmpl property. The template is compiled earlier in the code by calling the template() method. Finally, the Template Item update() method is called to re-render the Template Item with the bookDetailsTemplate instead of the original bookTemplate. Summary This is a long blog entry and I still have not managed to cover all of the features of jQuery Templates J However, I’ve tried to cover the most important features of jQuery Templates such as template composition, template wrapping, and template items. To learn more about jQuery Templates, I recommend that you look at the documentation for jQuery Templates at the official jQuery website. Another great way to learn more about jQuery Templates is to look at the (unminified) source code.

    Read the article

  • Cloning and renaming form elements with jQuery

    - by Micor
    I am looking for an effective way to either clone/rename or re-create address fields to offer ability to submit multiple addresses on the same page. So with form example like this: <div id="addresses"> <div class="address"> <input type="text" name="address[0].street"> <input type="text" name="address[0].city"> <input type="text" name="address[0].zip"> <input type="text" name="address[0].state"> </div> </div> <a href="" id="add_address">Add address form</a> From what I can understand there are two options to do that: Recreate the form field by field and increment the index which is kind of verbose: var index = $(".address").length; $('<`input`>').attr({ name: 'address[' + index + '].street', type: 'text' }).appendTo(...); $('<`input`>').attr({ name: 'address[' + index + '].city', type: 'text' }).appendTo(...); $('<`input`>').attr({ name: 'address[' + index + '].zip', type: 'text' }).appendTo(...); $('<`input`>').attr({ name: 'address[' + index + '].state', type: 'text' }).appendTo(...); Clone Existing layer and replace the name in the clone: $("div.address").clone().appendTo($("#addresses")); Which one do you recommend using in terms of being more efficient and if its #2 can you please suggest how I would go about search and replacing all occurrences of [0] with [1] ([n]). Thank you.

    Read the article

  • Help with this code.

    - by karthick6891
    Heading ##Hey guys i need help with this code.The short version is,i have to do match the follwing by using drag and drop in jquery and later i need to show a message whether it is right or wrong. var output = "Wrong"; var old_item ; var new_item ; var newObjArray=[]; $(function() { var $gallery = $('.gallery'), $trash = $('.trash'); $('div',$gallery).draggable({ revert: 'invalid', containment: 'document', helper: 'clone', cursor: 'move', }); // let the trash be droppable, accepting the gallery items $trash.droppable({ //accept: '#gallery div', //activeClass: 'ui-state-highlight', tolerance: 'touch', drop: function(ev, ui) { new_item = ui.draggable; $(this).droppable("option","activeClass",'.ui-state-highlight'); if(contains(newObjArray,ui.draggable)) { newObjArray.pop(ui.draggable); } newObjArray.push(ui.draggable); deleteImage(ui.draggable,$(this)); } }); // let the gallery be droppable as well, accepting items from the trash $gallery.droppable({ //accept: '#trash li', activeClass: 'custom-state-active', drop: function(ev, ui) { recycleImage(ui.draggable); } }); // image deletion function function deleteImage($item,element) { var $list; $item.fadeOut(10,function() { if($(".ui-widget-content", element).length <1){ old_item = $item; $list = $('<div class="gallery ui-helper-reset"/>').appendTo(element); //$('ul',$trash).length ? $('ul',$trash) : $('<ul class="gallery ui-helper-reset"/>').appendTo($trash); $item.appendTo($list).fadeIn(10); } else{ recycleImage($(".ui-widget-content",element)); $list = $('<div class="gallery ui-helper-reset"/>').appendTo(element); $item.appendTo($list).fadeIn(10); old_item = $item; } }); } //check for given answer // image recycle function function recycleImage($item) { $item.fadeOut(10,function() { $item.find("img").end().appendTo($gallery).fadeIn(10); }); } // image preview function, demonstrating the ui.dialog used as a modal window }); function checkOrder(){ if(newObjArray==null){ } else if(newObjArray!=null){ if(newObjArray[0].attr("id")=="5"&& newObjArray[1].attr("id")=="1" && newObjArray[2].attr("id")=="3" && newObjArray[3].attr("id")=="2" && newObjArray[4].attr("id")=="4"){ parent.parent.increaseCorrectA(); } else{ parent.parent.increaseWrongA(); } } } function contains(a, obj) { var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; } I am calling the function checkOrder() from the html page after the matching of items is over.What happens here is i have just stored the user responses on the draggable over droppable in an array,based on it's position.It is a bad practice cause,i am saying whether it's right or wrong through its position in the array.The only thing i can do is get the draggable's id present in the droppable.But i dont know how to get that inside the function checkOrder().Any ideas please?

    Read the article

  • Help with Nicedit - removeFormat function

    - by Franck
    Hello, I'm trying to get around Nicedit, and especially the "removeFormat" function. The problem is I cannot find the "removeFormat" method source code in the code below. The JS syntax looks strange to me. Can someone help me ? /* NicEdit - Micro Inline WYSIWYG * Copyright 2007-2008 Brian Kirchoff * * NicEdit is distributed under the terms of the MIT license * For more information visit http://nicedit.com/ * Do not remove this copyright message */ var bkExtend = function(){ var A = arguments; if (A.length == 1) { A = [this, A[0]] } for (var B in A[1]) { A[0][B] = A[1][B] } return A[0] }; function bkClass(){ } bkClass.prototype.construct = function(){ }; bkClass.extend = function(C){ var A = function(){ if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments) } }; var B = new this(bkClass); bkExtend(B, C); A.prototype = B; A.extend = this.extend; return A }; var bkElement = bkClass.extend({ construct: function(B, A){ if (typeof(B) == "string") { B = (A || document).createElement(B) } B = $BK(B); return B }, appendTo: function(A){ A.appendChild(this); return this }, appendBefore: function(A){ A.parentNode.insertBefore(this, A); return this }, addEvent: function(B, A){ bkLib.addEvent(this, B, A); return this }, setContent: function(A){ this.innerHTML = A; return this }, pos: function(){ var C = curtop = 0; var B = obj = this; if (obj.offsetParent) { do { C += obj.offsetLeft; curtop += obj.offsetTop } while (obj = obj.offsetParent) } var A = (!window.opera) ? parseInt(this.getStyle("border-width") || this.style.border) || 0 : 0; return [C + A, curtop + A + this.offsetHeight] }, noSelect: function(){ bkLib.noSelect(this); return this }, parentTag: function(A){ var B = this; do { if (B && B.nodeName && B.nodeName.toUpperCase() == A) { return B } B = B.parentNode } while (B); return false }, hasClass: function(A){ return this.className.match(new RegExp("(\s|^)nicEdit-" + A + "(\s|$)")) }, addClass: function(A){ if (!this.hasClass(A)) { this.className += " nicEdit-" + A } return this }, removeClass: function(A){ if (this.hasClass(A)) { this.className = this.className.replace(new RegExp("(\s|^)nicEdit-" + A + "(\s|$)"), " ") } return this }, setStyle: function(A){ var B = this.style; for (var C in A) { switch (C) { case "float": B.cssFloat = B.styleFloat = A[C]; break; case "opacity": B.opacity = A[C]; B.filter = "alpha(opacity=" + Math.round(A[C] * 100) + ")"; break; case "className": this.className = A[C]; break; default: B[C] = A[C] } } return this }, getStyle: function(A, C){ var B = (!C) ? document.defaultView : C; if (this.nodeType == 1) { return (B && B.getComputedStyle) ? B.getComputedStyle(this, null).getPropertyValue(A) : this.currentStyle[bkLib.camelize(A)] } }, remove: function(){ this.parentNode.removeChild(this); return this }, setAttributes: function(A){ for (var B in A) { this[B] = A[B] } return this } }); var bkLib = { isMSIE: (navigator.appVersion.indexOf("MSIE") != -1), addEvent: function(C, B, A){ (C.addEventListener) ? C.addEventListener(B, A, false) : C.attachEvent("on" + B, A) }, toArray: function(C){ var B = C.length, A = new Array(B); while (B--) { A[B] = C[B] } return A }, noSelect: function(B){ if (B.setAttribute && B.nodeName.toLowerCase() != "input" && B.nodeName.toLowerCase() != "textarea") { B.setAttribute("unselectable", "on") } for (var A = 0; A < B.childNodes.length; A++) { bkLib.noSelect(B.childNodes[A]) } }, camelize: function(A){ return A.replace(/-(.)/g, function(B, C){ return C.toUpperCase() }) }, inArray: function(A, B){ return (bkLib.search(A, B) != null) }, search: function(A, C){ for (var B = 0; B < A.length; B++) { if (A[B] == C) { return B } } return null }, cancelEvent: function(A){ A = A || window.event; if (A.preventDefault && A.stopPropagation) { A.preventDefault(); A.stopPropagation() } return false }, domLoad: [], domLoaded: function(){ if (arguments.callee.done) { return } arguments.callee.done = true; for (i = 0; i < bkLib.domLoad.length; i++) { bkLib.domLoadi } }, onDomLoaded: function(A){ this.domLoad.push(A); if (document.addEventListener) { document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null) } else { if (bkLib.isMSIE) { document.write(".nicEdit-main p { margin: 0; }<\/script"); $BK("__ie_onload").onreadystatechange = function(){ if (this.readyState == "complete") { bkLib.domLoaded() } } } } window.onload = bkLib.domLoaded } }; function $BK(A){ if (typeof(A) == "string") { A = document.getElementById(A) } return (A && !A.appendTo) ? bkExtend(A, bkElement.prototype) : A } var bkEvent = { addEvent: function(A, B){ if (B) { this.eventList = this.eventList || {}; this.eventList[A] = this.eventList[A] || []; this.eventList[A].push(B) } return this }, fireEvent: function(){ var A = bkLib.toArray(arguments), C = A.shift(); if (this.eventList && this.eventList[C]) { for (var B = 0; B < this.eventList[C].length; B++) { this.eventList[C][B].apply(this, A) } } } }; function __(A){ return A } Function.prototype.closure = function(){ var A = this, B = bkLib.toArray(arguments), C = B.shift(); return function(){ if (typeof(bkLib) != "undefined") { return A.apply(C, B.concat(bkLib.toArray(arguments))) } } }; Function.prototype.closureListener = function(){ var A = this, C = bkLib.toArray(arguments), B = C.shift(); return function(E){ E = E || window.event; if (E.target) { var D = E.target } else { var D = E.srcElement } return A.apply(B, [E, D].concat(C)) } }; var nicEditorConfig = bkClass.extend({ buttons: { 'bold': { name: _('Mettre en gras'), command: 'Bold', tags: ['B', 'STRONG'], css: { 'font-weight': 'bold' }, key: 'b' }, 'italic': { name: _('Mettre en italique'), command: 'Italic', tags: ['EM', 'I'], css: { 'font-style': 'italic' }, key: 'i' }, 'underline': { name: _('Souligner'), command: 'Underline', tags: ['U'], css: { 'text-decoration': 'underline' }, key: 'u' }, 'left': { name: _('Aligné à gauche'), command: 'justifyleft', noActive: true }, 'center': { name: _('Centré'), command: 'justifycenter', noActive: true }, 'right': { name: _('Aligné à droite'), command: 'justifyright', noActive: true }, 'justify': { name: _('Justifié'), command: 'justifyfull', noActive: true }, 'ol': { name: _('Liste non ordonnée'), command: 'insertorderedlist', tags: ['OL'] }, 'ul': { name: _('Liste non ordonnée'), command: 'insertunorderedlist', tags: ['UL'] }, 'subscript': { name: _('Placer en indice'), command: 'subscript', tags: ['SUB'] }, 'superscript': { name: _('Placer en exposant'), command: 'superscript', tags: ['SUP'] }, 'strikethrough': { name: _('Barrer le texte'), command: 'strikeThrough', css: { 'text-decoration': 'line-through' } }, 'removeformat': { name: _('Supprimer la mise en forme'), command: 'removeformat', noActive: true }, 'indent': { name: _('Indenter'), command: 'indent', noActive: true }, 'outdent': { name: _('Remove Indent'), command: 'outdent', noActive: true }, 'hr': { name: _('Ligne horizontale'), command: 'insertHorizontalRule', noActive: true } }, iconsPath: 'http://js.nicedit.com/nicEditIcons-latest.gif', buttonList: ['save', 'bold', 'italic', 'underline', 'left', 'center', 'right', 'justify', 'ol', 'ul', 'fontSize', 'fontFamily', 'fontFormat', 'indent', 'outdent', 'image', 'upload', 'link', 'unlink', 'forecolor', 'bgcolor'], iconList: { "xhtml": 1, "bgcolor": 2, "forecolor": 3, "bold": 4, "center": 5, "hr": 6, "indent": 7, "italic": 8, "justify": 9, "left": 10, "ol": 11, "outdent": 12, "removeformat": 13, "right": 14, "save": 25, "strikethrough": 16, "subscript": 17, "superscript": 18, "ul": 19, "underline": 20, "image": 21, "link": 22, "unlink": 23, "close": 24, "arrow": 26, "upload": 27, "question":2 } }); ; var nicEditors = { nicPlugins: [], editors: [], registerPlugin: function(B, A){ this.nicPlugins.push({ p: B, o: A }) }, allTextAreas: function(C){ var A = document.getElementsByTagName("textarea"); for (var B = 0; B < A.length; B++) { nicEditors.editors.push(new nicEditor(C).panelInstance(A[B])) } return nicEditors.editors }, findEditor: function(C){ var B = nicEditors.editors; for (var A = 0; A < B.length; A++) { if (B[A].instanceById(C)) { return B[A].instanceById(C) } } } }; var nicEditor = bkClass.extend({ construct: function(C){ this.options = new nicEditorConfig(); bkExtend(this.options, C); this.nicInstances = new Array(); this.loadedPlugins = new Array(); var A = nicEditors.nicPlugins; for (var B = 0; B < A.length; B++) { this.loadedPlugins.push(new A[B].p(this, A[B].o)) } nicEditors.editors.push(this); bkLib.addEvent(document.body, "mousedown", this.selectCheck.closureListener(this)) }, panelInstance: function(B, C){ B = this.checkReplace($BK(B)); var A = new bkElement("DIV").setStyle({ width: (parseInt(B.getStyle("width")) || B.clientWidth) + "px" }).appendBefore(B); this.setPanel(A); return this.addInstance(B, C) }, checkReplace: function(B){ var A = nicEditors.findEditor(B); if (A) { A.removeInstance(B); A.removePanel() } return B }, addInstance: function(B, C){ B = this.checkReplace($BK(B)); if (B.contentEditable || !!window.opera) { var A = new nicEditorInstance(B, C, this) } else { var A = new nicEditorIFrameInstance(B, C, this) } this.nicInstances.push(A); return this }, removeInstance: function(C){ C = $BK(C); var B = this.nicInstances; for (var A = 0; A < B.length; A++) { if (B[A].e == C) { B[A].remove(); this.nicInstances.splice(A, 1) } } }, removePanel: function(A){ if (this.nicPanel) { this.nicPanel.remove(); this.nicPanel = null } }, instanceById: function(C){ C = $BK(C); var B = this.nicInstances; for (var A = 0; A < B.length; A++) { if (B[A].e == C) { return B[A] } } }, setPanel: function(A){ this.nicPanel = new nicEditorPanel($BK(A), this.options, this); this.fireEvent("panel", this.nicPanel); return this }, nicCommand: function(B, A){ if (this.selectedInstance) { this.selectedInstance.nicCommand(B, A) } }, getIcon: function(D, A){ var C = this.options.iconList[D]; var B = (A.iconFiles) ? A.iconFiles[D] : ""; return { backgroundImage: "url('" + ((C) ? this.options.iconsPath : B) + "')", backgroundPosition: ((C) ? ((C - 1) * -18) : 0) + "px 0px" } }, selectCheck: function(C, A){ var B = false; do { if (A.className && A.className.indexOf("nicEdit") != -1) { return false } } while (A = A.parentNode); this.fireEvent("blur", this.selectedInstance, A); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; return false } }); nicEditor = nicEditor.extend(bkEvent); var nicEditorInstance = bkClass.extend({ isSelected: false, construct: function(G, D, C){ this.ne = C; this.elm = this.e = G; this.options = D || {}; newX = parseInt(G.getStyle("width")) || G.clientWidth; newY = parseInt(G.getStyle("height")) || G.clientHeight; this.initialHeight = newY - 8; var H = (G.nodeName.toLowerCase() == "textarea"); if (H || this.options.hasPanel) { var B = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat")); var E = { width: newX + "px", border: "1px solid #ccc", borderTop: 0, overflowY: "auto", overflowX: "hidden" }; E[(B) ? "height" : "maxHeight"] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight + "px" : null; this.editorContain = new bkElement("DIV").setStyle(E).appendBefore(G); var A = new bkElement("DIV").setStyle({ width: (newX - 8) + "px", margin: "4px", minHeight: newY + "px" }).addClass("main").appendTo(this.editorContain); G.setStyle({ display: "none" }); A.innerHTML = G.innerHTML; if (H) { A.setContent(G.value); this.copyElm = G; var F = G.parentTag("FORM"); if (F) { bkLib.addEvent(F, "submit", this.saveContent.closure(this)) } } A.setStyle((B) ? { height: newY + "px" } : { overflow: "hidden" }); this.elm = A } this.ne.addEvent("blur", this.blur.closure(this)); this.init(); this.blur() }, init: function(){ this.elm.setAttribute("contentEditable", "true"); if (this.getContent() == "") { this.setContent("") } this.instanceDoc = document.defaultView; this.elm.addEvent("mousedown", this.selected.closureListener(this)).addEvent("keypress", this.keyDown.closureListener(this)).addEvent("focus", this.selected.closure(this)).addEvent("blur", this.blur.closure(this)).addEvent("keyup", this.selected.closure(this)); this.elm.addEvent("resizestart",function(){return false}); this.elm.addEvent("dragstart",function(){return false}); this.ne.fireEvent("add", this); }, remove: function(){ this.saveContent(); if (this.copyElm || this.options.hasPanel) { this.editorContain.remove(); this.e.setStyle({ display: "block" }); this.ne.removePanel() } this.disable(); this.ne.fireEvent("remove", this) }, disable: function(){ this.elm.setAttribute("contentEditable", "false") }, getSel: function(){ return (window.getSelection) ? window.getSelection() : document.selection }, getRng: function(){ var A = this.getSel(); if (!A) { return null } return (A.rangeCount 0) ? A.getRangeAt(0) : A.createRange() }, selRng: function(A, B){ if (window.getSelection) { B.removeAllRanges(); B.addRange(A) } else { A.select() } }, selElm: function(){ var C = this.getRng(); if (C.startContainer) { var D = C.startContainer; if (C.cloneContents().childNodes.length == 1) { for (var B = 0; B < D.childNodes.length; B++) { var A = D.childNodes[B].ownerDocument.createRange(); A.selectNode(D.childNodes[B]); if (C.compareBoundaryPoints(Range.START_TO_START, A) != 1 && C.compareBoundaryPoints(Range.END_TO_END, A) != -1) { return $BK(D.childNodes[B]) } } } return $BK(D) } else { return $BK((this.getSel().type == "Control") ? C.item(0) : C.parentElement()) } }, saveRng: function(){ this.savedRange = this.getRng(); this.savedSel = this.getSel() }, restoreRng: function(){ if (this.savedRange) { this.selRng(this.savedRange, this.savedSel) } }, keyDown: function(B, A){ if (B.ctrlKey) { this.ne.fireEvent("key", this, B) } }, selected: function(C, A){ if (!A) { A = this.selElm() } if (!C.ctrlKey) { var B = this.ne.selectedInstance; if (B != this) { if (B) { this.ne.fireEvent("blur", B, A) } this.ne.selectedInstance = this; this.ne.fireEvent("focus", B, A) } this.ne.fireEvent("selected", B, A); this.isFocused = true; this.elm.addClass("selected") } return false }, blur: function(){ this.isFocused = false; this.elm.removeClass("selected") }, saveContent: function(){ if (this.copyElm || this.options.hasPanel) { this.ne.fireEvent("save", this); (this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent() } }, getElm: function(){ return this.elm }, getContent: function(){ this.content = this.getElm().innerHTML; this.ne.fireEvent("get", this); return this.content }, setContent: function(A){ this.content = A; this.ne.fireEvent("set", this); this.elm.innerHTML = this.content }, nicCommand: function(B, A){ document.execCommand(B, false, A) } }); var nicEditorIFrameInstance = nicEditorInstance.extend({ savedStyles: [], init: function(){ var B = this.elm.innerHTML.replace(/^\s+|\s+$/g, ""); this.elm.innerHTML = ""; (!B) ? B = "" : B; this.initialContent = B; this.elmFrame = new bkElement("iframe").setAttributes({ src: "javascript:;", frameBorder: 0, allowTransparency: "true", scrolling: "no" }).setStyle({ height: "100px", width: "100%" }).addClass("frame").appendTo(this.elm); if (this.copyElm) { this.elmFrame.setStyle({ width: (this.elm.offsetWidth - 4) + "px" }) } var A = ["font-size", "font-family", "font-weight", "color"]; for (itm in A) { this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm) } setTimeout(this.initFrame.closure(this), 50) }, disable: function(){ this.elm.innerHTML = this.getContent() }, initFrame: function(){ var B = $BK(this.elmFrame.contentWindow.document); B.designMode = "on"; B.open(); var A = this.ne.options.externalCSS; B.write("" + ((A) ? '' : "") + '' + this.initialContent + ""); B.close(); this.frameDoc = B; this.frameWin = $BK(this.elmFrame.contentWindow); this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles); this.instanceDoc = this.frameWin.document.defaultView; this.heightUpdate(); this.frameDoc.addEvent("mousedown", this.selected.closureListener(this)).addEvent("keyup", this.heightUpdate.closureListener(this)).addEvent("keydown", this.keyDown.closureListener(this)).addEvent("keyup", this.selected.closure(this)); this.ne.fireEvent("add", this) }, getElm: function(){ return this.frameContent }, setContent: function(A){ this.content = A; this.ne.fireEvent("set", this); this.frameContent.innerHTML = this.content; this.heightUpdate() }, getSel: function(){ return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection }, heightUpdate: function(){ this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight, this.initialHeight) + "px" }, nicCommand: function(B, A){ this.frameDoc.execCommand(B, false, A); setTimeout(this.heightUpdate.closure(this), 100) } }); var nicEditorPanel = bkClass.extend({ construct: function(E, B, A){ this.elm = E; this.options = B; this.ne = A; this.panelButtons = new Array(); this.buttonList = bkExtend([], this.ne.options.buttonList); this.panelContain = new bkElement("DIV").setStyle({ overflow: "hidden", width: "100%", border: "1px solid #cccccc", backgroundColor: "#efefef" }).addClass("panelContain"); this.panelElm = new bkElement("DIV").setStyle({ margin: "2px", marginTop: "0px", zoom: 1, overflow: "hidden" }).addClass("panel").appendTo(this.panelContain); this.panelContain.appendTo(E); var C = this.ne.options; var D = C.buttons; for (button in D) { this.addButton(button, C, true) } this.reorder(); E.noSelect() }, addButton: function(buttonName, options, noOrder){ var button = options.buttons[buttonName]; var type = (button.type) ? eval("(typeof(" + button.type + ') == "undefined") ? null : ' + button.type + ";") : nicEditorButton; var hasButton = bkLib.inArray(this.buttonList, buttonName); if (type && (hasButton || this.ne.options.fullPanel)) { this.panelButtons.push(new type(this.panelElm, buttonName, options, this.ne)); if (!hasButton) { this.buttonList.push(buttonName) } } }, findButton: function(B){ for (var A = 0; A < this.panelButtons.length; A++) { if (this.panelButtons[A].name == B) { return this.panelButtons[A] } } }, reorder: function(){ var C = this.buttonList; for (var B = 0; B < C.length; B++) { var A = this.findButton(C[B]); if (A) { this.panelElm.appendChild(A.margin) } } }, remove: function(){ this.elm.remove() } }); var nicEditorButton = bkClass.extend({ construct: function(D, A, C, B){ this.options = C.buttons[A]; this.name = A; this.ne = B; this.elm = D; this.margin = new bkElement("DIV").setStyle({ "float": "left", marginTop: "2px" }).appendTo(D); this.contain = new bkElement("DIV").setStyle({ width: "20px", height: "20px" }).addClass("buttonContain").appendTo(this.margin); this.border = new bkElement("DIV").setStyle({ backgroundColor: "#efefef", border: "1px solid #efefef" }).appendTo(this.contain); this.button = new bkElement("DIV").setStyle({ width: "18px", height: "18px", overflow: "hidden", zoom: 1, cursor: "pointer" }).addClass("button").setStyle(this.ne.getIcon(A, C)).appendTo(this.border); this.button.addEvent("mouseover", this.hoverOn.closure(this)).addEvent("mouseout", this.hoverOff.closure(this)).addEvent("mousedown", this.mouseClick.closure(this)).noSelect(); if (!window.opera) { this.button.onmousedown = this.button.onclick = bkLib.cancelEvent } B.addEvent("selected", this.enable.closure(this)).addEvent("blur", this.disable.closure(this)).addEvent("key", this.key.closure(this)); this.disable(); this.init() }, init: function(){ }, hide: function(){ this.contain.setStyle({ display: "none" }) }, updateState: function(){ if (this.isDisabled) { this.setBg() } else { if (this.isHover) { this.setBg("hover") } else { if (this.isActive) { this.setBg("active") } else { this.setBg() } } } }, setBg: function(A){ switch (A) { case "hover": var B = { border: "1px solid #666", backgroundColor: "#ddd" }; break; case "active": var B = { border: "1px solid #666", backgroundColor: "#ccc" }; break; default: var B = { border: "1px solid #efefef", backgroundColor: "#efefef" } } this.border.setStyle(B).addClass("button-" + A) }, checkNodes: function(A){ var B = A; do { if (this.options.tags && bkLib.inArray(this.options.tags, B.nodeName)) { this.activate(); return true } } while (B = B.parentNode && B.className != "nicEdit"); B = $BK(A); while (B.nodeType == 3) { B = $BK(B.parentNode) } if (this.options.css) { for (itm in this.options.css) { if (B.getStyle(itm, this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) { this.activate(); return true } } } this.deactivate(); return false }, activate: function(){ if (!this.isDisabled) { this.isActive = true; this.updateState(); this.ne.fireEvent("buttonActivate", this) } }, deactivate: function(){ this.isActive = false; this.updateState(); if (!this.isDisabled) { th

    Read the article

  • JQuery: Specify placement of error messages inline using Metadata and Validate plugins

    - by jalperin
    I'm doing form validation using JQuery with the validate and metadata plugins. I'm using the metadata plugin so I can specify the rules and messages inline in the html form instead of in the javascript in the page . I'm getting an error when I try to specify the location of the error message using errorPlacement. (If I specify it in the section it works fine, but not if I specify it inline.) Here's what my html looks like: <input name="list" id="list1" type="checkbox" validate="{required:true, minlength:1, messages:{required:'Please select at least one newsletter.', minlength:'Please select at least one newsletter.'}, errorPlacement: function(error, element) { error.appendTo('#listserror');} }"> As reported by the validate debug function, the error is: "error.appendTo is not a function." It works fine if I specify it in the section like this: $().ready(function() { $("#subscribeForm").validate({ errorPlacement: function(error, element) { if (element.attr("name") == "list" ) error.appendTo("#listserror"); else error.insertAfter(element); } }); });

    Read the article

  • get url:xml why external url does not work

    - by Kazim Cubbali
    I am trying to grab information from an external xml with the following code. It only worked when I uploaded same file to my servers. Why cant I grab information from an external url? <script language="javascript"> // This script uses jQuery to retrieve the news XML file and display the contents $(document).ready(function(){ $.ajax({ type: "GET", url: "www.simplyprofound.com/samples/xml_jquery/sample.xml", dataType: "xml", success: function(xml) { $(xml).find('item').each(function(){ var title = $(this).find('title').text(); var source = $(this).find('source').text(); var description = $(this).find('description').text(); $('<div class="news_title"></div>').html(title).appendTo('#news_wrap'); $('<div class="news_source"></div>').html(source).appendTo('#news_wrap'); $('<div class="news_description"></div>').html(description).appendTo('#news_wrap'); }); } }); }); </script>

    Read the article

  • Can't append to second container

    - by George Katsanos
    I have the following script: (function($) { $.fn.easyPaginate = function(options){ var defaults = { step: 4, delay: 100, numeric: true, nextprev: true, controls: 'pagination', current: 'current' }; var options = $.extend(defaults, options); var step = options.step; var lower, upper; var children = $(this).children(); var count = children.length; var obj, next, prev; var page = 1; var timeout; var clicked = false; function show(){ clearTimeout(timeout); lower = ((page-1) * step); upper = lower+step; $(children).each(function(i){ var child = $(this); child.hide(); if(i>=lower && i<upper){ setTimeout(function(){ child.fadeIn('fast') }, ( i-( Math.floor(i/step) * step) )*options.delay ); } if(options.nextprev){ if(upper >= count) { next.addClass('stop'); } else { next.removeClass('stop'); }; if(lower >= 1) { prev.removeClass('stop'); } else { prev.addClass('stop'); }; }; }); $('li','#'+ options.controls).removeClass(options.current); $('li[data-index="'+page+'"]','#'+ options.controls).addClass(options.current); if(options.auto){ if(options.clickstop && clicked){}else{ timeout = setTimeout(auto,options.pause); }; }; }; function auto(){ if(upper <= count){ page++; show(); } else { page--; show(); } }; this.each(function(){ obj = this; if(count>step){ var pages = Math.floor(count/step); if((count/step) > pages) pages++; var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>').insertAfter(obj); if(options.nextprev){ prev = $('<li class="prev">prev</li>') .appendTo(ol) .bind('click', function() { //check to see if there are any more pages in the negative direction if (page > 1) { clicked = true; page--; show(); } }); } if(options.numeric){ for(var i=1;i<=pages;i++){ $('<li data-index="'+ i +'">'+ i +'</li>') .appendTo(ol) .click(function(){ clicked = true; page = $(this).attr('data-index'); show(); }); }; }; if(options.nextprev){ next = $('<li class="next">next</li>') .appendTo(ol) .bind('click', function() { //check to see if there are any pages in the positive direction if (page < (count / 4)) { clicked = true; page++; show(); } }); } show(); }; }); }; })(jQuery); jQuery(function($){ $('ul.news').easyPaginate({step:4}); }); which is a carousel-like plugin that produces this html structure for the navigation: <ol id="pagination" class="pagin"><li class="prev">prev</li><li data-index="1" class="">1</li><li data-index="2" class="">2</li><li data-index="3" class="current">3</li><li class="next stop">next</li></ol> And all I want is to enclose this list in a div. Seems simple, but appendTo doesn't want to cooperate with me, or I'm doing something wrong (I'd appreciate if you would help me understand what that is..) So I'm modifying as such: var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>'); var tiv = $('<div id="lala"></div>'); ol.appendTo('#lala'); tiv.insertAfter(obj); I know how to chain, but I'm in "debugging" mode trying to understand why I don't get the result I imagine I would get: <div id="lala> <ol id="pagination><li>...... </li></ol> </div> I tried putting some console.log's to see the status of my variables but couldn't find something useful.. I guess there's something with DOM insertion I don't get.

    Read the article

  • how to clone the drag-event using jquery and jquery-ui.

    - by zjm1126
    i want to create a new '.b' div appendTo document.body, and it can dragable like its father, but i can not clone the drag event, how to do this, thanks this is my code : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta name="viewport" content="width=device-width, user-scalable=no"> </head> <body> <style type="text/css" media="screen"> </style> <div id="map_canvas" style="width: 500px; height: 300px;background:blue;"></div> <div class=b style="width: 20px; height: 20px;background:red;position:absolute;left:700px;top:200px;"></div> <script src="jquery-1.4.2.js" type="text/javascript"></script> <script src="jquery-ui-1.8rc3.custom.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(".b").draggable({ start: function(event,ui) { //console.log(ui) //$(ui.helper).clone(true).appendTo($(document.body)) $(this).clone(true).appendTo($(document.body))//draggable is not be cloned, } }); $("#map_canvas").droppable({ drop: function(event,ui) { //console.log(ui.offset.left+' '+ui.offset.top) ui.draggable.remove(); } }); </script> </body> </html>

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >