체크박스 checkbox 체크 된 목록 값만 가져오기

js API/jquery 2012. 4. 18. 17:37

jQuery를 이용해 특정 name 의 checkbox 중 체크된 값만 추출하기



특정 <li> 에 class="checkbox" 라는 클래스 명에 속에 있는 체크박스중

checkbox name="ads_com[]" 인것만 불러오기 하려는 목적입니당


# HTML /=========================




# 자바스크립트 /=============================

< script >
var com_uid_checkbox = '';
$("li.checkbox input:checkbox[name^=ads_com]:checked").each(function(){
	com_uid_checkbox+=','+$(this).val();
});
alert(com_uid_checkbox );
< /script >


# 결과

2,15


device (디바이스) 체크 및 종류 알아내기

js API/javascript 2012. 4. 10. 11:35

device (디바이스) 체크 및 종류 알아내기


1. JavaScript로 device (디바이스) 체크 및 종류 알아내기

각종 프로그래밍 언어 PHP, JSP등등으로 알아낼 수도 있지만
이건 자바스크립트로 접속 단말기를 알아내는 방법입니다.

함께 사용하면 더 편리합니다.




@ 디바이스 정보 알아내는 스크립트 function.js /================

< script >
//@ return String (device name)
function check_device(){
	var mobileKeyWords = new Array('iPhone', 'iPod', 'BlackBerry', 'Android', 'Windows CE', 'LG', 'MOT', 'SAMSUNG', 'SonyEricsson');
	var device_name = '';
	for (var word in mobileKeyWords){
		if (navigator.userAgent.match(mobileKeyWords[word]) != null){
			device_name = mobileKeyWords[word];
			break;
		}
	}
return device_name
}
< /script >


@ 활용 /========================================================

< script type="text/javascript" src="./js/function.js"  >< /script >
< script type="text/javascript" >
$(document).ready(function()
{
	// device check
	var device = check_device();
	if(device !=''){
		alert(device);
                // 모바일 페이지 이동 및 레이아웃 변경 작업 실행은 여기서 작성하심 됩니당
        }
});
< /script >


디바이스 정보를 알아 냈으니

원하는 작업을 하면 되겠죠?




2. PHP로 디바이스 정보 알아내기



@ 방법 1

< ?php
if (    strstr($_SERVER['HTTP_USER_AGENT'], "iPod") 
       || strstr($_SERVER['HTTP_USER_AGENT'], "iPhone")
       || strstr($_SERVER['HTTP_USER_AGENT'], "iPad")
       || strstr($_SERVER['HTTP_USER_AGENT'], "Mobile"))
 {
       // 모바일 페이지 이동 및 레이아웃 변경 작업 실행은 여기서 작성하심 됩니당
       header('Location: mobile.mysite.url');
       exit;
}
? >




@ 방법 2

< ?php
# 애플 제품인지 체크
function checkMobile() {
	if( preg_match( '/(iPod|iPhone|iPad|Android|Mobile)/', $_SERVER[ 'HTTP_USER_AGENT' ] ) ) {
		return 'true';
	} else {
		return 'false';
	}
}

if( checkMobile() ){
      // 모바일 페이지 이동 및 레이아웃 변경 작업 실행은 여기서 작성하심 됩니당
}
? >



jquery 활용 js 파일 include 하기

js API/jquery 2012. 4. 3. 15:55

jquery 활용 js 파일 include 하기


jquery를 이용해 js 파일들을 인클루드 하는 플러그인을 소개할까 합니다.
정말 유용한데요

먼저 include 해야할 js 파일을 한 후
순차적으로 js 파일을 인클루드 할 수 있도록 되어있습니다.

물론 jQuery 를 활용하기 때문에 jQuery는 먼저 불어 와 있어야 하겠죠? ^^



1. 기본환경설정
< script src="/common/js/jquery-1.7.1.min.js" >< /script >
< script src="/common/js/jquery.extended.js" >< /script >


2. 사용법
# 방법 1  /=========================
$.include(
	'js/my.js',
	// my.js 로딩 후 my1.js 를 로딩함
	$.include('js/my1.js')
);

# 방법 2 /==============================
$.include('js/my.js',
	// my.js를 먼저 로딩 후 my1.js, my2.js 를 불러 들입니다.
	[
		$.include('js/src/my1.js'),
		$.include('js/src/my2.js')
	]
);



@ jquery.extended.js 소스 /================
/**
 * $.include - script inclusion jQuery plugin
 * Based on idea from http://www.gnucitizen.org/projects/jquery-include/
 * @author Tobiasz Cudnik
 * @link http://meta20.net/.include_script_inclusion_jQuery_plugin
 * @license MIT
 */
// overload jquery's onDomReady
if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
	document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
	document.addEventListener( "DOMContentLoaded", function(){ jQuery.ready(); }, false );
}
jQuery.event.remove( window, "load", jQuery.ready );
jQuery.event.add( window, "load", function(){ jQuery.ready(); } );
jQuery.extend({
	includeStates: {},
	include: function(url, callback, dependency){
		if ( typeof callback != 'function' && ! dependency ) {
			dependency = callback;
			callback = null;
		}
		url = url.replace('\n', '');
		jQuery.includeStates[url] = false;
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.onload = function () {
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.onreadystatechange = function () {
			if ( this.readyState != "complete" && this.readyState != "loaded" ) return;
			jQuery.includeStates[url] = true;
			if ( callback )
				callback.call(script);
		};
		script.src = url;
		if ( dependency ) {
			if ( dependency.constructor != Array )
				dependency = [dependency];
			setTimeout(function(){
				var valid = true;
				$.each(dependency, function(k, v){
					if (! v() ) {
						valid = false;
						return false;
					}
				})
				if ( valid )
					document.getElementsByTagName('head')[0].appendChild(script);
				else
					setTimeout(arguments.callee, 10);
			}, 10);
		}
		else
			document.getElementsByTagName('head')[0].appendChild(script);
		return function(){
			return jQuery.includeStates[url];
		}
	},
	readyOld: jQuery.ready,
	ready: function () {
		if (jQuery.isReady) return;
		imReady = true;
		$.each(jQuery.includeStates, function(url, state) {
			if (! state)
				return imReady = false;
		});
		if (imReady) {
			jQuery.readyOld.apply(jQuery, arguments);
		} else {
			setTimeout(arguments.callee, 10);
		}
	}
});




jquery를 활용한 select 메뉴 컨트롤 메니저

js API/jquery 2012. 3. 29. 17:51

jquery 를 이용해 SELECT 메뉴를 손쉽게 컨트롤 해보자


좋은 소스를 만들어 주신 분께 먼저 감사합니다.
참 좋은 소스 인데요.

익스7, 8, 9, 오페라, 파이어폭스, 크롬, 사파리 에서 테스트 해 보았습니다.

다 잘 되더군요 역시 익스6은 안되는듯 ...
익스6은 버렸음 좋겠다 얼릉 사라졌음 하는 바램뿐

일단 jQuery 를 기반으로 만들어 졌기 때문에
jquery를 포함하고 있어야 합니다.

말보다 소스를 보시고
소스를 긁어다 테스트 해 보심이 더 빠를겁니다.


@ 자바 스크립트 /==========================================================

< script src="http://code.jquery.com/jquery.min.js" type="text/javascript">

< script type="text/javascript" >
var receiverMan = {
	itemList: null, // select option
	baseOption: {
		itemListSelector : 'select#itemList'
	},
	
	init: function(pOption) {
		this.baseOption = $.extend(this.baseOption, pOption);
		this.itemList = $(this.baseOption.itemListSelector);
	},
	selectedOptions: function() {
	    return this.itemList.find("option:selected");	
	}
	,
	add: function(data) {
		this.itemList.append($("").attr("value", data.value).text(data.text));
	}
	,
    del: function() {
    	// del selected all
    	this.selectedOptions().remove();
    }
	,
    clear: function() {
        // del all items
        this.itemList.find("option").remove();
    }
	,
    up: function() {        
    	var selectedOptions = this.selectedOptions();
    	var prev = $(selectedOptions).first().prev();
    	$(selectedOptions).insertBefore(prev);
    }
	,
    dn: function() {
    	var selectedOptions = this.selectedOptions();
        var next = $(selectedOptions).last().next();
        $(selectedOptions).insertAfter(next);
    }
	,
	selectedOne: function() {
		// return selected first item
		return { 
			value: this.selectedOptions().first().attr("value"),
			text:  this.selectedOptions().first().text()
			}
	}
	,
	selectedAll: function() {
        // return all selected item
		var r  = [];
		this.selectedOptions().each(function(idx, data) {
            r.push({
                value: $(this).attr("value"),
                text: $(this).text()
            });
        });
        return r;
    }
	,
   all: function() {
    	// return all
    	var r  = [];
	this.itemList.find("option").each(function(idx, data) {
    		r.push({
    			value: $(this).attr("value"),
                text: $(this).text()
    		});
    	});
    	return r;
    }
}



$(document).ready(function() {
	$('#receiverAdd').click(function() {
        receiverMan.add({text: 'test:'+(new Date().getTime()), value: '0001'  })
    });
    $('#receiverDel').click(function() {
        receiverMan.del();                
    });
    $('#receiverClear').click(function() {
        receiverMan.clear();                
    });
    $('#receiverUp').click(function() {
    	receiverMan.up();
    });
    $('#receiverDown').click(function() {
    	receiverMan.dn();
    });
    
	receiverMan.init({
		// itemListSelector : "your SELECT selector"
		itemListSelector : "select#itemList"
	});

	$('#itemList').change(function(){
		var args= receiverMan.selectedOne();
		alert(args['value']+' '+args['text']);
	});

	// 자동 등록 레이어 테스트 
	for(var i=0; i<7; i++){
		receiverMan.add({text: 'test:'+(new Date().getTime()), value: '000'+i  })
	}
});
< /script >


@ css /===============================================
< style text="text/css" >
.receiverInputBox {
    width: 500px;
}
.itemList {
    width:300px;
    height:20px;
    font-size:100%;
    color:blue;
    background-color:#ffffff;
    border:0px solid #ffffff;
}
< /style >





@ html /===============================================
< div>
    < div>
        < select name="itemList" id="itemList" class="itemList">
        < a href="#" id="receiverAdd">Add/
        < a href="#" id="receiverDel">Delete/
        < a href="#" id="receiverClear">Clear/
        < a href="#" id="receiverUp">Up/
        < a href="#" id="receiverDown">Down
    < /div>
< /div>


jquery json IE, Opera 등 parse error 발생 할때

js API/jquery 2012. 3. 15. 11:02
우리는 jquery 를 이용해서 서버와의 통신을 자주 하게 됩니다.
그런데 dataType : 'json'  으로 ajax 통신을 할때

크롬을 제외한 IE 등에서 parse error 를 발생합니다.
정말 난감할 뿐만 아니라 어처구니가 없는거죠

jquery 가 잘 만들어 졌지만 브라우저 마다 처리 방법들이 조금씩 다르다 보니
모두 호환 되도록 하는 방법 밖에 없는 것 같습니다.

그리하여 해결 방법은 이렇습니다.

@ Javascript /=====================================
< script >
function jsonAjax(uid)
{

   $.ajax({
    type: "post",
    url: "./test_json.php",
    cache: false,
    dataType :'text',
    data: {'uid':uid},
    success: function(data, status){
           var json = eval("(" + data + ")");
         // OR  var json =$.parseJSON(data);
           
	  if(typeof(json.result) != 'undefined')
	  {
		if(json.result != ''){
			alert(json.result);
		}else{
			$("#list_loop").empty(); //초기화
			$.each(json.msg, function(key,state) {
				$("#list_loop").append('
'+state["userid"]+' ('+state["name"]+')
'); }); } } }, error: onError }); return false; } function onError(data, status, errorThrown){ alert(data.responseText+' '+status+' '+errorThrown); } < /script >


@ PHP /============================================
<?php
# 회원정보 루프 배열 값
$loop[0] = array(
    'userid' => 'test1id',
    'name'  => '홍길동'
);

$loop[1] = array(
    'userid' => 'test1id',
    'name'  => '홍길동'
);


# json 최종결과
$args = array(
    'result' => 'ok',
    'msg'   => $loop
);

echo json_endcode($args);
exit;
?>

@ HTML /===========================================
< div id="list_loop"> 여기에 내용 결과 출력 < /div >



1. jquery를 이용한 ajax 통신을 할때 dataType 를 text 로 합니다.
2. text 값으로 받은 값을 eval 를 통해 json 데이타로 변환 한다.