星期五, 11月 09, 2012

[jQuery plugin] 如何reset from

jquery validator常常submit完要重新清除,常用到的語法。
在此記錄一下。

$(form)[0].reset();

[jQuery plugin] validator fileupload


記錄如何驗證上傳元素,只要加上accept,filesize即可。

 fileToUpload:{ 
accept: "png|jpe?g|gif",
filesize: 1048576
 }

[jQuery plugin] Validator 如何在選擇元素select驗證

常常會用到的validator於選擇元素上的驗證,原來也是加個required就好,記一下 XD

$("#bankForm").validate({
   rules:{
    
     citys:{
     required:true
     }
                     
});
最後發現請選擇的option的value要記得設"",不然會無法動作。

                               
                           

星期六, 11月 03, 2012

[Javascript] 檢查json的key是否存在



太常用到了,記錄一下。使用hasOwnProperty就可以輕鬆解決嚕 wow

You don't need jQuery for this, just JavaScript. You can do it a few ways:
  • typeof d.failed- returns the type ('undefined', 'Number', etc)
  • d.hasOwnProperty('failed')- just in case it's inherited
  • 'failed' in d- check if it was ever set (even to undefined)

星期四, 11月 01, 2012

[Alfresco] Upload Avatar Javascript API


//js

/**
 * User Profile Avatar Upload method
 *
 * @method POST
 * @param username {string}
 *        filedata {file}
 */

function main()
{
   try
   {
      var filename = null;
      var content = null;
      var username = null;

      // locate file attributes
      for each (field in formdata.fields)
      {
         if (field.name == "filedata" && field.isFile)
         {
            filename = field.filename;
            content = field.content;
         }
         else if (field.name == "username")
         {
            username = field.value;
         }
      }

      // ensure all mandatory attributes have been located
      if (filename == undefined || content == undefined)
      {
         status.code = 400;
         status.message = "Uploaded file cannot be located in request";
         status.redirect = true;
         return;
      }
      if (username == null || username.length == 0)
      {
         status.code = 500;
         status.message = "Username parameter not supplied.";
         status.redirect = true;
         return;
      }

      var user = people.getPerson(username);
      // ensure we found a valid user and that it is the current user or we are an admin
      if (user == null ||
          (people.isAdmin(person) == false && user.properties.userName != person.properties.userName))
      {
         status.code = 500;
         status.message = "Failed to locate user to modify or permission denied.";
         status.redirect = true;
         return;
      }

      // ensure cm:person has 'cm:preferences' aspect applied - as we want to add the avatar as
      // the child node of the 'cm:preferenceImage' association
      if (!user.hasAspect("cm:preferences"))
      {
         user.addAspect("cm:preferences");
      }

      // remove old image child node if we already have one
      var assocs = user.childAssocs["cm:preferenceImage"];
      if (assocs != null && assocs.length == 1)
      {
         assocs[0].remove();
      }

      // create the new image node
      var image = user.createNode(filename, "cm:content", "cm:preferenceImage");
      image.properties.content.write(content);
      image.properties.content.guessMimetype(filename);
      image.properties.content.encoding = "UTF-8";
      image.save();

      // wire up 'cm:avatar' target association - backward compatible with JSF web-client avatar
      assocs = user.associations["cm:avatar"];
      if (assocs != null && assocs.length == 1)
      {
         user.removeAssociation(assocs[0], "cm:avatar");
      }
      user.createAssociation(image, "cm:avatar");

      // save ref to be returned
      model.image = image;
   }
   catch (e)
   {
      var x = e;
      status.code = 500;
      status.message = "Unexpected error occured during upload of new content.";
      if(x.message && x.message.indexOf("org.alfresco.service.cmr.usage.ContentQuotaException") == 0)
      {
         status.code = 413;
         status.message = x.message;
      }
      status.redirect = true;
      return;
   }
}

main();



//description

  Avatar Upload
  Upload avatar file content and apply to person preferences
 
  user
  required
  /slingshot/profile/uploadavatar



//template
{
<#if person.childAssocs["cm:preferenceImage"]??>
"avatar": "${person.childAssocs["cm:preferenceImage"][0].downloadUrl}"
</#if>
<#if person.associations["cm:avatar"]??>
<#if person.associations["cm:avatar"][0].childAssocs["rn:rendition"]??>
,"avatarthumb": "${person.associations["cm:avatar"][0].childAssocs["rn:rendition"][0].downloadUrl}"
</#if>
</#if>
}

星期三, 10月 24, 2012

[Java] 取得Image的byte[]

今天廠商在哭爸圖片解析度太低,只好先把JPEG壓縮拿掉。
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(encoderOutputStream);
encoder.encode(bufferedResizedImage);
查了一下如何把BufferedImage轉成Byte[]存在db,或你其他的需求。
BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
這篇文章好心整理了java中的幾個處理方法,有空可以看看。
High-Quality Image Resize with Java

星期日, 10月 21, 2012

[Javascript] Callback function

Callback在寫oop的javascript中非常好用, 找到了一篇非常容易理解的好文章。
Callback Functions in JavaScript
function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    if (callback && typeof(callback) === "function") {
        callback();
    }
}

mySandwich('ham', 'cheese', 'vegetables');

星期六, 10月 20, 2012

[jQuery] ajax 異常錯誤

昨天遇到一個很奇怪的AJAX呼叫錯誤, 最後發現觸發的元素內的javascript:void(0)打錯了,導致JS異常=.= 找了一陣子才找到,真是扯XD

星期二, 10月 16, 2012

[JSON] 取得json keys 列表

原本都用陣列來儲存列表,這次遇到用keys來表示原本陣列的數量<
for (var key in repaymentlist) 
  {
   if (repaymentlist.hasOwnProperty(key))
   {
    $.console(repaymentlist[key]);
    
   }
  }

星期四, 10月 11, 2012

[Javascript] 取得物件的類別名稱

如果取得你自訂類別的名稱

function getClassName(obj) {
if (typeof obj != "object" || obj === null) return false;
return /(\w+)\(/.exec(obj.constructor.toString())[1];
}

星期三, 9月 26, 2012

[jQuery] ie8 元素id與js變數產生衝突

今天程式發生了一個IE8 bug,因使用js來做前端的i18n,但同事有把元素的id取得跟i18n js的變數一樣,導致js錯誤發生。

 HTML
<span id=”stupid_ie_8”></span>

//i18n key
stup_ie_8 = “IE好弱”;

//script
$(“#stupid_ie_8”).html(stup_ie_8);

星期二, 9月 25, 2012

[jQuery] append function error in IE8

今天被fire一個bug,有關於append元素的時候,畫面沒有被顯示。
主要是append的元素結構沒有正常的結尾,ie8無法自動修正。

一般html頁面元素沒有正常結尾也會空白

星期三, 9月 19, 2012

[jQuery API] 拍賣倒數計時器 min seconds: 倒數十下

現在所有團購網都流行的倒數計時器方法,參考至某團購網站XD

$(function() {
    setInterval(function () {
  var m = parseInt($('#mis').text());
  //console.log("start m:" + m);
  if (isNaN(m)) {
   $('#mis').text('0');
  } else {
   m=m+10;
   //console.log("m:" + m);
   if (m>=10) { 
    m=m-1;   
    if(m>=10)
    {
     $('#mis').text(m-10);
    }
    else
    {
     $('#mis').text(m);
    }
   } 
  }
 }, 100);//setInterval
 });  

星期六, 9月 15, 2012

[jQuery plugin] jquery Validator表單驗證器 番外篇(進階一點的需求吧XD)

Validator真是好物呀,先前有整理一個入學篇,覺得篇福愈來愈長了,
遇到的新問題就記在這篇吧!!

Q.如何指定要特地驗證某一個欄位
有時候你只想要透過別的動作來檢查某個欄位,可以使用valid方法,回傳值為1:驗證通過,0:驗證失敗

var validateForMoney = $("#borrowMoney").valid()//1:ok,0:false
$.console("validateForMoney:" + validateForMoney);
var validateForRate = $("#borrowRate").valid();
$.console("validateForRate:" + validateForRate);

Q.取得全部驗證失敗的欄位有哪些?
//透過numberOfInvalids方法就會回傳數字了,$validatedPostBorrow是我驗證器的變數
$.console("invalid fields:" + $validatedPostBorrow.numberOfInvalids());


Reference:
jQuery Validate Plugin - Trigger validation of single field

星期二, 9月 04, 2012

[jQuery plugin] 來個倒數計時器吧

倒數計時器能增加使用者有感的提示XD常用到拍賣商品上的特效。
找了幾個現成的元件
請參考以下這篇網誌的20以上的jQuery countdown plugins (有擷圖)
http://www.tripwiremagazine.com/2012/05/jquery-countdown-scripts.html

星期一, 9月 03, 2012

[jQuery API] 實作Facebook的捲軸拉到底更新資訊 Facebook like scroll bar detection

如何使用jQuery偵測捲軸的位置!! 實作Facebook like的更新狀態列記錄
$(function () {
             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0)
                     alert('Scrolled to Page Top');
                 else if ($win.height() + $win.scrollTop()
                                == $(document).height()) {
                     alert('Scrolled to Page Bottom');
                 }
             });
         });


Here's some explanation:

$(window).height() - returns height of browser viewport

$(document).height() - returns height of HTML document

$(window).scrollTop() – returns the current vertical position of the scroll bar.

So if the scroll bar is at the very top, the value of $(window).scrollTop() will be Zero. Similarly if the value of the browser viewport + vertical position of scroll bar = document height, then the user has scrolled to the bottom of the page.

寫成外掛的方式來看看!!

其他你感興趣的文章

Related Posts with Thumbnails