顯示具有 JQuery 標籤的文章。 顯示所有文章
顯示具有 JQuery 標籤的文章。 顯示所有文章

2020年6月8日 星期一

ASP.NET WebForm RadioButtonList 使用JQuery取得使用者所選擇的項目

參考資料1:[jQuery] RadioButtonList 取值


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="js/jquery-1.11.3.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('input[type="radio"][name="<%=RBL1.UniqueID %>"]').change(function () {
                var SelectVal = $(this).val();
                var SelectText = $(this).closest('td').find('label').text(); //用closest取得radio上一層的td,並取得label的text
                $('#<%=Label1.ClientID%>').text(SelectText+':');

            });
//法1.請看參考資料1
            //$('#<%=Label1.ClientID%>').text($('input:radio[name="<%=RBL1.UniqueID %>"]:checked + label').text()+':');
//法2.先取得RadioButtonList預設選取哪一個項目,並用closest取得radio上一層的td,並取得label的text
            $('#<%=Label1.ClientID%>').text($('input:radio[name="<%=RBL1.UniqueID %>"]:checked').closest('td').find('label').text()+':');
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
    查詢方式:
            <asp:RadioButtonList ID="RBL1" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Selected="True" Value="0">姓名</asp:ListItem>
                <asp:ListItem Value="1">學號</asp:ListItem>
            </asp:RadioButtonList>
            <br/>
            <asp:Label ID="Label1" runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </div>
    </form>
</body>
</html>

2014年11月13日 星期四

ASP.NET WebForm + JQuery RadioButtonList變更時,啟用DropDownList控制項

本篇直接使用JQuery來啟用或停用DropDownList,重點不使用ASP.NET的AJAX功能

前置作業:請先到JQuery官方網站下載jquery(我是使用v1.8.2)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="./Scripts/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //小於%=RBL_bhours.UniqueID %大於 是ASP的寫法,會將RBL_bhours控制項的唯一識別印出(類似ID)
            $('input[type="radio"][name="<%=RBL_bhours.UniqueID %>"]').change(function () {
                var bhours = this.value;
                //會先找到id="div1" 再 循序處理每個 select元素
                $('#div1 select').each(function () {
                    if (bhours == 'true') {
                        $(this).removeAttr('disabled'); //移除disabled等於啟用select元素
                    } else {
                        $(this).attr('disabled', 'disabled'); //加入disabled等於停用select元素
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList ID="RBL_bhours" runat="server"
            RepeatDirection="Horizontal" RepeatLayout="Flow">
            <asp:ListItem Value="true">開啟</asp:ListItem>
            <asp:ListItem Value="false" Selected="True">關閉</asp:ListItem>
        </asp:RadioButtonList>
        &nbsp;&nbsp;
        <div id="div1">
            每月
            <asp:DropDownList ID="DDL_ts" runat="server" Width="45px" Enabled="false">
                <asp:ListItem>01</asp:ListItem>
                <asp:ListItem>02</asp:ListItem>
                <asp:ListItem>03</asp:ListItem>
            </asp:DropDownList>日
            到
            每月
            <asp:DropDownList ID="DDL_te" runat="server" Width="45px" Enabled="false">
                <asp:ListItem>01</asp:ListItem>
                <asp:ListItem>02</asp:ListItem>
                <asp:ListItem>03</asp:ListItem>
            </asp:DropDownList>日
        </div>
    </form>
</body>
</html>

2014年6月20日 星期五

JQuery UI accordion 設定標題、內容位置、cookie紀錄目前點擊的項目

參考1:asp.net+jquery accordion 按鈕點擊會收縮

說明:參考1的資料符合我要實作的需求,在此作了些補充及修改。另外下方的程式碼,少了另外一個登入的頁面,當使用者登入成功後,將會指定 $.cookie('index',0); ,轉到另外一個頁面(下方的程式碼)後accordion就會預設展開我們要展開的項目,因為有指定cookie的關係,當使用者重新整理時,accordion就會停留在目前點擊的項目。

程式碼如下
<head>
    <title></title>
    <link rel="stylesheet" href="themes/base/jquery.ui.all.css">
    <script type="text/javascript" src="Scripts/jquery.js"></script>
    <script src="Scripts/jquery.cookie.js"></script>
<script src="Scripts/jquery.ui.core.js"></script>
<script src="Scripts/jquery.ui.widget.js"></script>
    <script src="Scripts/jquery.ui.accordion.js"></script>
<script>
   $(function () {
//同時設定 active: false,collapsible: true 可讓項目呈現不摺疊(不展開)狀態
$('#accordion').accordion({
activate: function (event, ui) {
   //當click時觸發此處
if (($.cookie('index') == null) || ($.cookie('index')==undefined)) {
$.cookie('index', 0);
}else{
$.cookie('index', $('#accordion').accordion('option', 'active'));
};
},
active: parseInt($.cookie('saved_index'),10),
collapsible: true,
});
   });
</script>
    <style>
/**設定摺疊標題文字大小 padding: .5em .5em .5em .7em;*/
.ui-accordion .ui-accordion-header { display: block; font-size: 16px; }
/*設定摺疊標題為置**/
.ui-accordion .ui-accordion-icons {padding-left: 1.5em;}
/**.ui-accordion .ui-accordion-content 設定摺疊內容文字位置*/
.ui-accordion .ui-accordion-content {padding: 0.5em 0.5em; border-top: 0; overflow: auto; zoom: 1;}
    </style>
    <link type="text/css" rel="stylesheet" href="public_css.css"/>
</head>
<body>
    <form id="form1">
<div id="accordion">
<h4>項目1</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目2</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目3</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
</div>
    </form>
</body>
</html>

2014年6月6日 星期五

JQuery 應用篇

201706
1.取得table中的td欄位資料。
//jquery-1.11.3.js
$('#table1 > tbody > tr').each(function () {
//nth-child(3)取得第4個欄位資料
//$(this).find('td:nth-child(3)').text().trim()
 //如果要取得欄位中的TextBox就使用eq,取得第5個欄位的input
 //$(this).find('td:eq(4) input[type="text"]').val();
});
2.取得table中第一列之後的所有資料。
通常第一列會是表頭,如果要取得第一列之後的資料列,請使用下方的程式碼。
//:not排除、:first表格的第一列
//:not(:first)除了表格的第一行,其他的資料列都要
$('#table1 > tbody > tr:not(:first)').each(function () {
...
});

201705
1.檢查元素存不存在可以使用length來判斷,等於0不存在、>0代表存在。
if ($('#span_mess').length > 0) {
  //存在
}else{
  //不存在
};

201512
1.設定某個容器底下的checkbox全部勾選、全部取消(此例以table底下的checkbox為例)
//使用 jquery 版本v1.8.2
function CB1_checked(str_pid, int_dis) {
if (int_dis==1) {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', true); //全部勾選
} else {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', false); //全部取消
};
};

201411
1. 移除屬性(removeAttr)
$('#button1').removeAttr('onclick'); //移除button1 onclick

2. readonly
$('#id1').attr('readonly',true);

201406
1. HTML radio
1-1. 取得 radio 是否有選取項目
var str_iden=$('input[type="radio"][name="iden"]:checked').val();
if (str_iden==undefined){
    alert('您的身份尚未填寫');
    return false;  //在script標籤中,回傳false 會有終止程式執行的效果
};

1-2. radio 單選某個項目
$('input[type="radio"][name="iden"][value="1"]').attr("checked",true);

1-3. radio 停用與啟用
$('#input[type="radio"][name="iden"]').attr('disabled',true); //停用

1-4. 取得class是sall的元素,底下input type是radio,其值是1的項目(個人覺得如果是使用asp.net建議使用prop)。
$('[class="sall"] input[type="radio"][value="1"]').prop("checked", true);

2. HTML Checkbox
2-1. checkbox 是否有勾選此項目(適用於單一一個checkbox)
法1.
if ($('input[type="checkbox"][name="tt"]').attr('checked')){
   alert('您已勾選此項目');
}else{
   alert('您已取消此項目');
};

法2.(適用於JQuery 1.6以後的版本)
將 $('input[type="checkbox"][name="tt"]').attr('checked') 改成
$('input[type="checkbox"][name="tt"]').prop('checked')

2-2. 設定CheckBox勾選
$('input[type="checkbox"][name="tt"]').attr('checked',true); //可用在低版本的JQuery

補充:使用 attr('checked', true) 與 prop("checked", true)差別在於attr('checked', true)會在標籤裡增加checked的屬性,而 prop("checked", true)則不會在標籤裡增加checked屬性。

3. HTML Select
2-1. 取得下拉式選單選取的值及項目
$('select[name="s1"] option:selected').val();  //value
$('select[id="DDL1"] option:selected').text(); //項目

2-2. 設定下拉式選單項目為選取狀態(適用於JQuery低版本)
$('select[name="Area"] option[value="100"]').attr("selected",true);

2018/03/26 如果我的Html Select有設定class,例如我的class="hello",我也可以這樣子去設定Select要停留在哪一個選項。(使用的jquery版本是jquery-1.11.3)
$('.hello').val('0');

2014年2月22日 星期六

JQuery 記錄使用者點擊li,重整後顯示點擊的li

只記錄使用者目前點擊的項目,不包含使用者點擊過哪些項目

參考資料:
jQuery教學-點選開啟下拉選單

前置作業:
使用JQuery-v1.6.4

Code:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>記錄點擊li,重整後顯示點擊的li</title>
<script src="js/jquery.min.js" language="javascript"></script>
<script>
$(function(){
       //cookie不等於0
if( document.cookie.length!=0 ){
   var s_value=document.cookie.search('click_item=');//search字串搜尋,沒有找到為-1;
var e_value,str_CookTemp;
if( s_value!=-1 ){
s_value=s_value+('click_item='.length);
e_value=document.cookie.indexOf(';', s_value);
if( e_value==-1 ){
      e_value=document.cookie.length;
   }
str_CookTemp=document.cookie.slice(s_value,e_value);
//使用parents()可以取得DOM中的html元素;find搜索所有段落
var get_li=$('.menu ul:eq('+(str_CookTemp)+')').parents('li').find('a[href="#"]');
var str_title=get_li.html(); //取得title名稱
str_title=str_title.replace("►","▼");
get_li.html(str_title); //變更標題名稱
get_li.next().show();
}
}
$(".menu li a").click(function(){
var _this=$(this);
var on_li=$(this).closest('li'); //取得a上一層的li
var li_index=on_li.index(); //記錄li的index
document.cookie='click_item='+li_index+';'; //記錄點了哪一個li
if(_this.next("ul").length>0){
if(_this.next().is(":visible")){
//隱藏子選單並替換符號
_this.html(_this.html().replace("▼","►")).next().hide();
}else{
//開啟子選單並替換符號
_this.html(_this.html().replace("►","▼")).next().show();
}
//關閉連結
return false;
}
});

});
</script>
<style>
a{color:#333333; text-decoration:none; font-size:12px;}
a:hover{text-decoration:underline;}
ul{margin:0;padding:0;list-style-type: none;}
ul.submenu{display:none;}
ul.submenu{margin-left:25px;list-style-type:disc; color:#333333;}
</style>
</head>
<body>
<ul id="ulid" class="menu">
<li>
    <a href="#">►abc公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
        </ul>
    </li>
<li>
    <a href="#">►def公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
            <li><a href="http://localhost/" target="_blank">部門3</a></li>              
        </ul>
    </li>
    <li>
    <a href="#">►ghi公司</a>
    <ul class="submenu">
        <li><a href="http://localhost/" target="_blank">部門1</a></li>
            <li><a href="http://localhost/" target="_blank">部門2</a></li>
            <li><a href="http://localhost/" target="_blank">部門3</a></li>
            <li><a href="http://localhost/" target="_blank">部門4</a></li>      
        </ul>
    </li>  
</ul>
</body>
</html>

2013年11月28日 星期四

jquery mobile 切換頁面到html檔無法執行javascript

參考1: http://www.jqmobile.org/thread-254-1-1.html
參考2: http://liuwenxin.blog.51cto.com/4436000/1032260

問題:用a標記的href鏈接跳轉到目的頁面時,綁定的$(document).ready()不執行,需要刷新頁面才能執行?
解決:jquery mobile頁面跳轉是ajax跳轉,所以$(document).ready()是不執行的,如果想用a標記跳轉過來執行一些函數的話有兩種方法:
(1).用js的window.location.href=url跳轉,或者在a標記裡寫rel="external",這樣頁面就脫離了jquery mobile框架,到了一個新的頁面;
(2).給目的頁面的page加一個id,例如:indexPage,給indexPage綁定pageinit事件,$('#indexPage').live('pageinit',function(event){});就可以了,其實jquery mobile頁面的跳轉就是不同page直接的切換

法1: 如果你原本的超連結標籤是寫成<a href="news.htm" >最新消息</a> 當去點選此連結時,切換到news.htm時,它是不會執行javascript的程式碼,必須在標籤上多加上rel="external"寫法如下  <a href="news.htm" rel="external">最新消息</a>

2013年9月24日 星期二

JavaScript replace 字數計算,取代空白、換行

前置作業:
請自行下載JQuery檔案以及建置好開發ASP的環境。
重點在於如何使用JavaScript來計算使用者在輸入文字時,如何計算字數。

紅色字為重點

<%@CODEPAGE="65001"%>
<%
'輸出設定成UTF-8'
Response.CodePage = 65001  
Response.CharSet = "utf-8"

'在使用傳統ASP時,為了避免使用者按"上一頁"看到Client的暫存網頁,通常會加上下列這三行'
Response.CacheControl = "no-cache"
Response.AddHeader "Pragma", "no-cache"
Response.Expires = -1

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文件</title>
<script type="text/javascript" src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
var str_factor=/(\s)|(\n)/g;
$(document).ready(function(){
       //運用JQuery為input id=TB1加入keyup事件
$('#TB1').keyup(function(){
var Word_Number;
var str_temp2 = $('#TB1').val(); //取得input id=TB1的值
if (str_temp2.replace(str_factor, "").length==0) {
$("#SSWl").html(''); //將 div id=SSWl 文字清空
}else{
Word_Number=(str_temp2.replace(str_factor, "")).length;
$("#SSWl").html('目前字數:'+Word_Number);
$('#showmsg').html($('#TB1').val());
}
});
});

function checkform(){
var str_temp = "";
if ($('#TB1').val() == '' || $.trim($('#TB1').val()).length - 1 == -1) {
alert('未填寫');
return false;
} else {
str_temp = $('#TB1').val();
if ((str_temp.replace(str_factor, "")).length < 10) {
alert('字數小於10個字,\n必須至少10個字');
return false;
}else if ((str_temp.replace(str_factor, "")).length > 10){
if ((str_temp.replace(str_factor, "")).length > 50){
 alert('字數最多不能大於50個字');
 return false;
}
}
}
window.document.f1.submit();
}
</script>
</head>
<body>
<%
TB1=Request.Form("TB1")
if NOT ISEmpty(TB1) then
   Response.write "NOT Empty<br />"
   str_temp=replace(TB1,vbcrlf,"" )
   str_temp=replace(str_temp," ","" )
   Response.write "長度="& len(str_temp) & ";" & str_temp '&nbsp;空白符號
else
   Response.write "Empty"
end  if
%>
<div id="SSWl"></div>
<form method="post" name="f1" id="f1" action="test_TextBox.asp" enctype="application/x-www-form-urlencoded">
  <textarea name="TB1" id="TB1" style="width: 450px; height: 180px"></textarea>
  <input type="submit" value="送出" onclick="javascript:checkform();"/>
</form>
<br />
<span id="showmsg">?</span>
</body>
</html>

JavaScript 顏色16進位轉RGB 或 RGB轉16進位

最近剛好碰到Html5的<input type="color"/>
當我選擇好顏色的時候,取到的值會是#ff0000,但有時開發人員會想取得RGB的值也就是RGB(255,255,255),您可以參考這篇資料 Convert rgb color to hex color


程式碼如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Pragma" content="No-cache" />
<title>顏色16進位轉RGB 或 RGB轉16進位</title>
<script src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
//RGB轉16進位
function rgb2hex(rgb){
   var hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
   var hex = function(x){
       return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
   };
   var tmp = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
   var color = hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3]);
   return color;
}
//16進位轉RGB
function hex2rgb(v){
   if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(v.toUpperCase())) {
       if (v.length == 3) {
           v = v.match(/[0-9A-F]/g);
           v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2];
           this.value = v;
       }
   
       var r = parseInt(v.substr(0, 2), 16);
       var g = parseInt(v.substr(2, 2), 16);
       var b = parseInt(v.substr(4, 2), 16);
       return [r, g, b].join(',');
   }
   return v;
}
var hex,rgb;
//背景色
$('#BColor').change(function(){
  hex=$('#BColor').val().replace('#', ''); //將#字號取代掉
  rgb ='rgb('+hex2rgb(hex)+')';
  alert(rgb);
});
</script>
</head>
<body>
Bg:<input type="color" id="BColor"/>
</body>
</html>

2013年8月20日 星期二

Html div 水平垂直置中

今日在Google找資料key入了關鍵字:div 水平垂直置中,找到了以下這篇資料
CSS 教學 – 設定一個 div 水平置中和垂直置中
此篇是以圖片來做教學示範,所以您有需要可以看此篇,但建議您先看此篇,講解比較清楚。

而我今日想在網頁中將文字水平垂直置中,那麼要怎麼設定Html div標籤呢,因為文字在div標籤中會改變height、width,那如果將來要修改div裡面的文字這樣以後一定又要修改CSS或Html碼,所以自己就利用JQuery來計算位置自動去調整div位置,這樣將來就不需要修改CSS或Html碼,即使div增加了文字也不需要去調整。

前置作業:
  請自行到JQuery下載jquery-2.0.2.min.js

以下是Code,註解都在程式碼中,在此不再作解釋
Html:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>div水平垂直置中</title>
<style type="text/css">
body {
background-color: #EEE; /*背景色*/
}
.BOX {
border: 2px solid #444;
box-shadow: 5px 5px 5px #666;

position:absolute; /*position制定位置*/
top:50%; /* top 座標為 50% */
left:50%; /* left 座標為 50% */
}
</style>
<!--引用JQuery檔jquery-2.0.2.min.js-->
<script type="text/javascript" src="js/jquery-2.0.2.min.js"></script>
<script type="text/javascript">
    $(function () {
 var h=$('#divbox').height(); //取得div標籤,id為divbox的高度
 var w=$('#divbox').width();  //取得div標籤,id為divbox的寬度
 //計算位移margin-top,margin-left數值
 var margin_top=-(h/2);
 var margin_left=-(w/2);
       
          //為div標籤,id是divbox加入CSS
 $('#divbox').css({'margin-top':margin_top,'margin-left':margin_left});
    });
</script>
</head>
<body>
<!--class="BOX"會套用CSS的.BOX-->
<div class="BOX" id="divbox">
    <h1 style=" text-align:center;">
    目前網頁未開放<br />
    Current page is not open.
    </h1>
</div>
</body>
</html>

2013年7月23日 星期二

ASP.NET、HTML 限制TextBox輸入的資料

重點紀錄與整理:實作TextBox限制使用者只能輸入英文及數字符號、限制使用者不能剪下複製貼上、運用css限制TextBox使輸入法失效。

Default5.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default5.aspx.vb" Inherits="Default5" %>

<!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 runat="server">
<script src="jquery-2.0.1.min.js"></script>
<script>
$(function () {
$('#TextBox1').bind('cut copy paste', function (e) {
e.preventDefault(); //取消動作
alert('禁止剪下複製貼上');
});
$('#Html_TextBox').bind('cut copy paste', function(e) {
    e.preventDefault(); //取消動作
    alert('禁止剪下複製貼上');
});
});
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        實作TextBox限制只能輸入英文及數字符號、限制使用者不能剪下複製貼上、運用css限制TextBox使輸入法失效<br />
        以下為ASP.NET TextBox控制項<br />
        <asp:TextBox ID="TextBox1" runat="server" Height="110px" style="ime-mode:Disabled;"
            TextMode="MultiLine" Width="276px"></asp:TextBox><br />
        以下為HTML TextBox多行輸入控制項<br />
        <textarea rows="10" style="width: 271px;ime-mode:Disabled;" id="Html_TextBox" onkeyup="value=value.replace(/^a-zA-Z0-9/)"></textarea>
        <asp:Button ID="Button2" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Default5.aspx.vb
Partial Class Default5
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        '為ASP.NET TextBox控制項加入客戶端onkeyup事件用運javascript的replace函式搭配正規表示式來限制使用者輸入的資料
        TextBox1.Attributes("onkeyup") = "value=value.replace(/^a-zA-Z0-9/)"
    End Sub

End Class

說明
1. style="ime-mode:Disabled;" 利用CSS來限制使用者僅能輸入英文和數字及符號;其實在程式碼當中也有寫到JavaScript語法的replace函式來限制使用者僅能輸入英文和數字及符號,在這裡就看您想用哪一種方法來限制使用者所輸入的資料

資料來源:
[jQuery] TextBox中禁止剪下複製貼上
輕鬆解決網頁只能輸入英數字的問題

2013年7月6日 星期六

ASP.NET 利用JQuery設定控制項選取項目、啟用、隱藏

有時候我們可能在寫程式時會寫到SQL查詢功能,又或者會寫到表單的填寫,在網頁上都會有一些像是DropDownList(下拉式選單)控制項,當我選了某一個項目時就會啟用另外一個控制項,通常為了達到這樣的效果,都會去設定DropDownList控制項的AutoPostBack屬性,這時當我選取下拉式選單的項目時,就會去啟用另外一個控制項,就會照成頁面的刷新,如果不想要讓頁面刷新,那你就必須再使用ajax控制項的UpdatePanel,來達成非同步的更新。如果不想要這麼作,那還有另外一個方法就是在網頁上寫JavaScript、JQuery等語法來完成。

功能敘述:當我選取DDL1下拉式選單時,就會啟用另外一個DDL2下拉式選單,當我又選取DDL2的學生姓名選項時,又會去將隱藏起來的TextBox顯示出來,讓使用者進去條件的查詢。

前置作業:
1.先新增一個網頁名為:Default2.aspx

HTML:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!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 runat="server">
    <title></title>
    <script src="jquery-2.0.1.min.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DDL1" runat="server">
            <asp:ListItem Value="-1">請選擇查詢方式</asp:ListItem>
            <asp:ListItem Value="0">未測驗</asp:ListItem>
            <asp:ListItem Value="1">不合格者</asp:ListItem>
            <asp:ListItem Value="2">合格者</asp:ListItem>
        </asp:DropDownList>&nbsp;
        <asp:DropDownList ID="DDL2" runat="server" Enabled="false">
            <asp:ListItem Value="-1">全部</asp:ListItem>
            <asp:ListItem Value="0">學生姓名</asp:ListItem>
        </asp:DropDownList>&nbsp;
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="查詢" Enabled="false"/>
    </div>
    </form>
</body>
</html>

後置程式碼:
Imports System.Text
Partial Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim str_js As New StringBuilder

        str_js.Append("$(document).ready(function(){")
        str_js.Append("$('#" & TextBox1.ClientID & "').hide();")
        str_js.Append("$('#" & DDL1.ClientID & "').change(")
        str_js.Append("function(){")
        str_js.Append("var str_text=$('#" & DDL1.ClientID & "').find(':selected').text();") '取得被選擇項目的文字
        str_js.Append("var str_value=$('#" & DDL1.ClientID & "').find(':selected').val();") '取得被選擇項目的值
        'true停用,啟用它就設成false;再asp.net控制項則是相反enabled=true為啟用,enabled=false則不啟用
        str_js.Append("if(parseInt(str_value)==-1){$('#" & DDL2.ClientID & "').attr('disabled',true);" & _
                      "$('#" & DDL2.ClientID & "').find('option:eq(0)').attr('selected', true);" & _
                      "$('#" & Button1.ClientID & "').attr('disabled',true);" & _
                      "$('#" & TextBox1.ClientID & "').hide();" & _
                      "}else{$('#" & DDL2.ClientID & "').attr('disabled',false);" & _
                      "$('#" & Button1.ClientID & "').attr('disabled',false);}")
        str_js.Append("});")
        str_js.Append("$('#" & DDL2.ClientID & "').change(")
        str_js.Append("function(){")
        str_js.Append("var str_value2=$('#" & DDL2.ClientID & "').find(':selected').val();")
        str_js.Append("if(parseInt(str_value2)==-1){$('#" & TextBox1.ClientID & "').hide();" & _
                     "}else{$('#" & TextBox1.ClientID & "').show();}")
        str_js.Append("});")
        str_js.Append("});")

        If ScriptManager.GetCurrent(Page) Is Nothing Then
            '未啟用asp.net ajax功能
            '有些情況下會需要以動態的方式加入用戶端指令碼。 若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Default2", str_js.ToString, True)
        Else
            '啟用asp.net ajax功能
            ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Default2", str_js.ToString, True)
        End If
    End Sub
End Class

說明:
1. <script src="jquery-2.0.1.min.js"></script> 引用JQuery檔案,要引用才能撰寫JQuery
2.有人會發現,我將JQuery寫在後置程式碼裡,透過RegisterClientScriptBlock方法將撰寫好的JQuery直接插入到html裡(你可以按滑鼠右鍵→檢視原始檔,就會發現JQuery程式碼已經插入到html當中),就可以執行JQuery程式碼
其餘改日再補充...

2013年6月22日 星期六

ASP.NET 使用JQuery全部取消GridView中的CheckBox

如題,有些人有寫過ASP.NET的應該都會知道,也應該會想說我只要寫一個For迴圈再去抓GridView中的CheckBox就可以了,但當你剛開始接觸JQuery(初學者)時,你可能會想說我何不透過JQuery去抓GirdView中的CheckBox呢?
我是這麼想的...直接抓全部的 input再取得類型(type)是CheckBox把它取消就可以了,這樣的好處是我不用再寫For迴圈去一個一個抓CheckBox控制項,也能輕易的抓到全部的CheckBox囉

如何實做,請看程式碼,並請實際操作...程式碼如下:

Default.aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!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 runat="server">
<script src="jquery-2.0.1.min.js"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="全部取消" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField HeaderText="CheckBox">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="test_id" HeaderText="test_id" InsertVisible="False"
                    ReadOnly="True" SortExpression="test_id" />
                <asp:BoundField DataField="test_name" HeaderText="test_name"
                    SortExpression="test_name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [test_T]"></asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

Default2.aspx.vb:
Imports System.Text
Partial Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim str_js As New StringBuilder
        str_js.Append("function CB_CFalse(){")
        str_js.Append("$('input[type=checkbox]:checked').each(function () {")
        str_js.Append("$(this).attr('checked', false);")
        str_js.Append("})")
        str_js.Append("}")
        Button1.Attributes("onclick") = "CB_CFalse();"
        '假如未啟用asp.net ajax功能
        If ScriptManager.GetCurrent(Page) Is Nothing Then
            '有些情況下會需要以動態的方式加入用戶端指令碼。
            '若要動態加入指令碼,請使用 RegisterClientScriptBlock 方法、RegisterClientScriptInclude 方法、RegisterStartupScript 方法或 RegisterOnSubmitStatement 方法,視您要加入指令碼的時間和方式而定。
            'RegisterStartupScript方法會在最後面插入javascript程式碼
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "wjs2", str_js.ToString, True)
        Else
            '否則有啟用asp.net ajax功能
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "wjs2", str_js.ToString, True)
        End If
    End Sub
End Class

說明:
1.<script src="jquery-2.0.1.min.js"></script>特別注意紅色標起來的這一行,您必須去JQuery的官方網站下載檔案,這個檔案有分版本,請自行下載。
2.$('input[type=checkbox]:checked').each  $為JQuery的簡易寫法,括號內的input就是抓html的input,type=checkbox就是抓input屬於checkbox的類型,運用each去抓每一個chekcbox
3.$(this).attr('checked', false);  this就是目前的checkbox,去設定checked=false

以上如有說明錯誤請指點,感謝...