Skip to content

Instantly share code, notes, and snippets.

@Qooh0
Last active December 21, 2021 04:56
Show Gist options
  • Save Qooh0/f85d5ffce89dcafc9d6a12b55a38926a to your computer and use it in GitHub Desktop.
Save Qooh0/f85d5ffce89dcafc9d6a12b55a38926a to your computer and use it in GitHub Desktop.
JQuery-tips
// 全角→半角(英数字)
function replaceFullToHalf(str){
return str.replace(/[!-~]/g, function(s){
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
});
}
// 半角→全角(英数字)
function replaceHalfToFull(str){
return str.replace(/[!-~]/g, function(s){
return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);
});
}
// カタカナ→ひらがな
function replaceKanaToHira(str){
return str.replace(/[\u30a1-\u30f6]/g, function(s){
return String.fromCharCode(s.charCodeAt(0) - 0x60);
});
}
// ひらがな→ひらがな
function replaceHiraToKana(str){
return str.replace(/[\u3041-\u3096]/g, function(s){
return String.fromCharCode(s.charCodeAt(0) + 0x60);
});
}
// 空欄チェック
$("#xxxxx").blur(() => {
if ($("#xxxxx").val().indexOf(" ") !== -1) { attachErrorStyle($("#xxxxx")); }
else { attachStandardStyle($("#xxxxx")); }
});
function attachErrorStyle(ele, color = "#f8d7da") { ele.css('background-color', color) };
function attachStandardStyle(ele, color = "") { ele.css('background-color', color) };
// ふりがな、カタカナ、ー、漢字、全角半角スペースの許可
$("input[name='hoge']").blur(function(){
if(!$(this).val().match(/^[ぁ-んァ-ヶー一-龠  \r\n\t]+$/)){
}
});
// カタカナ、ー、全角半角スペースを許可
$("input[name='hoge']").blur(function(){
if(!$(this).val().match(/^[ァ-ロワヲンー  \r\n\t]*$/)){
}
});
// ハイフン、数字に反応
$("input[name='hoge']").blur(function(){
if(!$(this).val().match(/^[0-9\-]+$/)){
}
});
// ハイフンを削除して数字のみにする
$("input[name='hoge']").blur(function(){
$hyphen = $(this).val().replace(/[━.*‐.*―.*-.*\–.*ー.*\-]/gi,''); $(this).val($hyphen)
if(!$(this).val().match(/^[0-9]+$/)){
//事項内容
}
});
// HTML を拒否
$("textarea[name='hoge']").blur(function(){
if($(this).val().match(/[<(.*)>.*<\/\1>]/)){
alert('HTMLコードが含まれます。')
}
});
// スペース、改行コード、タブコードのみに反応
$("input[name='hoge']").blur(function(){
if($(this).val().match(/^[  \r\n\t]*$/)){
//実行内容
}
});
// --SELECT BOX--
// 何番目を選択しているか
$("#xxxxx").prop('selectedIndex')

よく使う発火イベント

  1. onclick
  2. onchange
  3. focus/focusin フォーカスがあたった時。 focursin は form 要素に対しても使える 1 blur/focusout フォーカスが外れた時. focursout は form 要素に対しても使える
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment