공부하면 별거 아니지만 은근히 안외워지고 그때그때 자꾸 검색해야해서 기록함..

예제입니다. 간단히...^^

#체크박스 선택시 해당 tr의 원하는 td값 가져오기

라디오 버튼 클릭시 칸2의 값을 가져옵니다...해당칸까지 포함해서 계산합니다.

// 버튼 클릭 이벤트 처리
$("#but").on("click", function() {
// 체크된 체크박스들의 3번째 칸 데이터 출력

$("input[name=poizon]:checked").each(function(index) {
var $row = $(this).closest("tr"); // 체크된 체크박스가 속한 행
var thirdCellText = $row.find("td:nth-child(3)").text(); // 3번째 칸의 텍스트 조회
var thirdCellText = $row.find("td").eq(2).text(); // 3번째 칸의 텍스트 조회
console.log("선택된 2번째 칸 데이터: " + thirdCellText);
});

var chose=$("input[name=poizon]:checked");
var tr_1 = chose.closest("tr");
var td_3 =tr_1.find("td:nth-child(3)").text();
console.log(td_3);
});

each를 통하면  tr의 td값을 순서대로 출력도 가능함.

$("input[name=poizon]:checked").each(function () {
var $row = $(this).closest("tr"); // 체크된 체크박스가 속한 행
var rowData = ""; // 행의 데이터를 저장할 변수

// 행의 각 셀 데이터를 조회하여 rowData에 추가합니다.
$row.find("td").each(function () {
rowData += $(this).text() + " | ";
});

// 마지막에는 "|" 구분자를 제거하고 데이터를 출력합니다.
console.log("선택된 행 데이터: " + rowData.slice(0, -3));
});

#라디오 버튼 선택시 해당 tr만 배경색 바꾸기....

$('input[name=poizon]').change(function() {
var chose=$("input[name=poizon]:checked");
// Get the parent row of the radio
var row = chose.closest('tr');
$('tr').css("background-color","");
row.css("background-color","gray");

});

css로 간단히 변경이 가능하다.

'JQUERY' 카테고리의 다른 글

게시판아코디언  (0) 2022.08.25
<!-- 1. 폼 회원가입에서 회원가입 버튼을 클릭하면 result.html로 이동한다.

2. 아이디, 패스워드, 패스워드확인, 이름, 이메일 모든 항목은 반드시 입력해야 한다.

3. 아이디는 라벨을 클릭해도 해당 입력 상자로 포커스 이동한다.

4. 취소 버튼을 이용해서 입력 상자를 초기화 한다.

5. 아이디는 입력시 첫글자는 대문자이고 나머지 글자는 영문자, 숫자로 4글자 이상만 가능하다.

6. 아이디 입력 후 포커스가 이동할 경우에 조건 체크 한다.

7. 조건 체크에 만족하지 않으면 '4글자이상, 첫글자는 대문자이고 영문자, 숫자만 가능" 이라는 대화 상자가 나타난다.

8. 입력한 아이디 값도 삭제한다.

9. 패스워드 입력 하지 않고 패스워드확인을 입력한 경우 "패스워드를 입력하세요"라는 대화 상자가 나타나고

패스워드확인 값 삭제하고 패스워드 입력 상자로 포커스 이동한다.

패스워드 입력창 옆에 패스워드와 패스워드확인이 일치하면 '패스워드가 일치합니다'라는 문자를 초록색 진하게 출력하고,

일치하지 않으면 '패스워드가 일치하지 않습니다'를 빨간색으로 진하게 출력한다.

10. 성별입력은 회원가입 버튼을 클릭시 남 또는 여 radio 버튼 선택여부 확인한다.

성별입력을 선택하지 않은 경우 "성별을 선택하세요"라는 메시지 출력하고 submit 이벤트 발생하지 않는다. -->

<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>

<script>

$(function(){

$('#userId').blur(function(){

var value=$('#userId').val().trim();

var reg=/^[A-Z][A-Za-z0-9]{3,}/;

if(!reg.test(value))

{

alert("4글자이상, 첫글자는 대문자이고, 영문자, 숫자만 가능");

$('#userId').val('');

}

});

$('#check_pw').keyup(function(){

var pw1=$('#password').val().trim();

if(pw1==""){

alert("패스워드를 입력하세요");

$('#check_pw').val('');

$('#password').focus();

}

var pw2=$('#check_pw').val().trim();

if(pw1.length!=0 && pw2.length!=0){

if(pw1==pw2)

{

$('#out').html("패스워드가 일치합니다.");

$('#out').css({'color':'green','font-weight':'bolder'});

}

else{

$('#out').html("패스워드가 일치하지 않습니다.");

$('#out').css({'color':'red','font-weight':'bolder'});

}

}

});

$("form").submit(function(){

var rcheck= $(".gender1:checked").length;

if(rcheck==0){

alert("성별을 선택하세요");

return false;

}

})

});

</script>

<style>

form ul{list-style: none;}

form ul>li{text-align:right;width:100px;

display: inline-block; margin-right:5px}

form li:last-child{

width:300px;

text-align: center;

}

</style>

</head>

<body>

<form action="result.html" method="post">

<fieldset>

<legend>회원가입</legend>

<ul>

<li><label for="userId">아이디</label></li>

<li><input type="text" name='userId' id="userId" size='10' required></li><br>

<li><label for="password">패스워드</label></li>

<li><input type="password" name='password' id="password" size='10' required></li><span id="out"></span>

<br>

<li><label for='check_pw'>패스워드확인</label></li>

<li><input type="password" id="check_pw" size='10' required></li><br>

<li><label for='userName'>이름</label></li>

<li><input type="text" name='userName' id="userName" size='10' required></li><br>

<li>성별</li>

<li><label>남<input type="radio" name='gender' class="gender1" value="M"></label>   

<label>여<input type="radio" name='gender' class="gender1" value="F"></label></li>

<br>

<li><label for='email'>이메일</label></li>

<li><input type="email" name='email' id="email" size='10' required></li><br><br>

<li>

<input type="submit" value="회원가입">   

<input type="reset" value="취소">

</li>

</ul>

</fieldset>

</form>
<h3>키보드 관련 이벤트</h3>
    <p>
        keydown : 키가 눌렸을 때 <br>
        keypress : 키가 눌리는 동안 <br>
        keyup : 키에서 손을 떼었을때
    </p>

     연습 : <input type="text" id="test2"><br>
     <span id="result">0</span>

     <script>
        //keydown/ keypress / keyup
        $('#test2').on('keyup',function(){
            var cnt = $(this).val().length;
            console.log(cnt);
            $('#result').text(cnt);
         });
     </script>
 
<script>
        //keydown/ keypress / keyup
        $('#test2').on('keyup',function(){
            var cnt = $(this).val().length;
            console.log(cnt);
            $('#result').text(cnt);
         });
     </script>
    <h3>동적 글자수 세기</h3>
    <div>
        <h1 id="counter">100</h1>
        <textarea id="contents" cols="70" rows="4"></textarea>
    </div>
    <script>
        $('#contents').on('keyup',function(){
            var words=$(this).val().length;
            var remain=100-words;

            $('#counter').html(remain);
            if(remain<0) {
                $('#counter').css('color','red');
            }else if(remain<11){
                $('#counter').css('color','blue');
            }else{
                $('#counter').css('color','black');
            }
        });
    </script>

'JQUERY > 함수' 카테고리의 다른 글

hover()  (0) 2022.08.28
이벤트..mouseout. mouseover  (0) 2022.08.28
이벤트 연결함수...on.off  (0) 2022.08.28
요소 복사,삭제태그들....clone(),remove()  (0) 2022.08.28
요소추가. append, prepend, before, after  (0) 2022.08.28
 <h3>hover()함수 : enter와 leave</h3>
    <p>
        mouseenter + mouseleave
    </p>
    <h1 id="test1">hover Test !</h1>

    <script>
        $(function(){
            $('#test1').hover(
              function(){$(this).css('background','yellow')},
              function(){$(this).css('background','green')}  
            );
        });

    </script>

<head>
    <meta charset="UTF-8">
    <title>연결가능 이벤트</title>
    <script src="../RESOURCES/asset/js/jquery-3.6.0.min.js"></script>
    <style>
        .outer{
            margin: 50px;
            width: 200px;
            height: 200px;
            background-color: aquamarine;
        }
        .inner{
            margin: 25px;
            width: 150px;
            height: 150px;
            background-color: green;
            position: absolute;
        }
    </style>

</head>
<body>
    <h1>연결가능 이벤트</h1>
    <h3>마우스 관련 이벤트</h3>
    <div class="outer">
        <div class="inner"></div>
    </div>
    <script>
        $(function(){
        /*    $('.outer').on('mouseenter',function(){
                console.log("Enter 발생!!");
            });
            $('.outer').on('mouseleave',function(){
                console.log("Leave발생!!");
            });
            */arguments
            $('.outer').on('mouseout',function(){
                console.log("out 발생!!!")
            });
            $('.outer').on('mouseover',function(){
                console.log("Over 발생!!")
            });
        });
    </script>

'JQUERY > 함수' 카테고리의 다른 글

키보드관련//글자수세기  (0) 2022.08.28
hover()  (0) 2022.08.28
이벤트 연결함수...on.off  (0) 2022.08.28
요소 복사,삭제태그들....clone(),remove()  (0) 2022.08.28
요소추가. append, prepend, before, after  (0) 2022.08.28
<body>
    <h1>이벤트</h1>
    <button onclick="test1(event);">실행확인</button>
    <script>
        function test1(event){
            //이벤트 내장객체(javascript)
            console.log('이벤트');
        }
    </script>

 

    <h3>이벤트 연결 함수</h3>
    <p>
        bind()/on() :  현재 존재하는 요소를 이벤트와 연결하는 함수 <br>
        unbind() / off() : 현재 연결된 이벤트를 요소로 부터 제거하는 함수 <br>
        jQurey 3버전 부터 on/off함수로 대체 되었다.
    </p>
    <div id="test1">마우스<br>이벤트</div>
   <script>
        //bind/unbind
   /*     $(function(){
            $('#test1').bind('mouseenter',function(){
                $(this).css({
                    background : 'orange'
                });
            }).bind('mouseleave',function(){
                $(this).css({
                    background:'white'
                });
            });
            $('#test1').bind('click',function(){
                $(this).unbind('mouseenter').unbind('mouseleave');
            });
        });

        */
       //on()/off()
       $('#test1').on({
        'mouseenter':function(){
            $(this).css('background','yellow').text('마우스 올라감');
        },
        'mouseleave':function(){
            $(this).css('background','green').text('마우스 떠남');
        },
        'click':function(){
            $(this).off('mouseenter').off('mouseleave');
        }
       });

    </script>

 

   <hr>
    <h3>one() : 일회성 함수</h3>
    <button id="testOne">실행 확인</button>

    <script>
        $('#testOne').one('click',function(){
            alert('실행 확인하였습니다.');
        });
    </script>

 

'JQUERY > 함수' 카테고리의 다른 글

hover()  (0) 2022.08.28
이벤트..mouseout. mouseover  (0) 2022.08.28
요소 복사,삭제태그들....clone(),remove()  (0) 2022.08.28
요소추가. append, prepend, before, after  (0) 2022.08.28
요소추가. append, prepend, before, after  (0) 2022.08.28
 <hr>
    <h3>요소 복사/ 삭제하기</h3>
    <p>
        clone():지정한 요소를 복제할 때 사용 <br>
        remove() /detach()/ empty() :
        요소를 삭제하거나 안의 내용을 텅~비울때 사용<br>
        remove(): 요소자체를 지움<br>
        detach(): 요소의 모양은 지우나 연결되었던 이벤트는 남겨둠 <br>
        empty(): 요소안의 내용을 비움
    </p>
    <div id="cloneTest">
        <div class="item" id="item1">
            <button class="copy">복사하기</button>
            <button class="delete">삭제하기</button>
        </div>
        <div class="item" id="item2">
            <button class="copy">복사하기</button>
            <button class="delete">삭제하기</button>
        </div>
        <div class="item" id="item3">
            <button class="copy">복사하기</button>
            <button class="delete">삭제하기</button>
        </div>
    </div>
    <hr>
    <div id="result"></div>
    <script>
        $(function(){
            $('.copy').click(function(){
                //clone()/clone(true/false) 둘중 선택/
                //clone()/clone(false): 모양 복사, 연결된 이벤트 기능없음
                $(this).parent().clone(true).appendTo($('#result'));  
                // $(A).appendTo(B) : A -> B 안에 마지막 추가             
            });
            $('.delete').click(function(){
                //empty(), detach(),remove()
                // $(this).empty(); 클릭한 것만 사라지고 부모태그는 그대로임.
              //  $(this).parent().parent().empty(); //복사 전체 삭제된다.
              //$(this).parent().detach();  //임시저장 공간에 남겨둔다
              $(this).parent().remove(); //많이쓴다.
            });
        });
    </script>
 
    <h3>요소 추가 2</h3>
    <p>
        $(A).append(B) : B -> A 안에 마지막 추가  <br>
        $(A).prepent(B) : B -> A 안에 첫번째에 추가 <br>
        $(A).before(B) : B 를 A 앞에 추가<br>
        $(A).after(B) : B를 A 뒤에 추가 <br>
    </p>
    <!--h1#test5>laber{|과일박스|}-->
    <h1 id="test5">
        <laber>|과일박스|</laber>
    </h1>
    <script>
        $(function(){
            var interval=setInterval(function(){
                //$('#test5').append('사과');
                //$('#test5').prepend('배');
                //$('#test5').before('오렌지');
                $('#test5').after('수박');
                setTimeout(function(){
                    clearInterval(interval);
                },3000);
            },1000);
        });
    </script>
    <h3>요소 추가 2</h3>
    <p>
        $(A).append(B) : B -> A 안에 마지막 추가  <br>
        $(A).prepent(B) : B -> A 안에 첫번째에 추가 <br>
        $(A).before(B) : B 를 A 앞에 추가<br>
        $(A).after(B) : B를 A 뒤에 추가 <br>
    </p>
    <!--h1#test5>laber{|과일박스|}-->
    <h1 id="test5">
        <laber>|과일박스|</laber>
    </h1>
    <script>
        $(function(){
            var interval=setInterval(function(){
                //$('#test5').append('사과');
                //$('#test5').prepend('배');
                //$('#test5').before('오렌지');
                $('#test5').after('수박');
                setTimeout(function(){
                    clearInterval(interval);
                },3000);
            },1000);
        });
    </script>
<h1>요소(태그)추가 /삭제 함수</h1>
    <p>
        $(A).apppendTo(B) : A -> B 안에 마지막 추가  <br>
        $(A).prepentTo(B) : A -> B 안에 첫번째에 추가 <br>
        $(A).insertBefore(B) : A 를 B 앞에 추가(동위요소) <br>
        $(A).insertAfter(B) : A를 B 뒤에 추가 <br>
    </p>    

    <!--(h1#test$>laber{ - 기준 - })*4-->
    <h1 id="test1">
        <laber> - 기준 - </laber>
    </h1>
    <h1 id="test2">
        <laber> - 기준 - </laber>
    </h1>
    <h1 id="test3">
        <laber> - 기준 - </laber>
    </h1>
    <h1 id="test4">
        <laber> - 기준 - </laber>
    </h1>

    <script>
        $(function(){
            var interval = setInterval(function(){
                $('<laber>appendTo()</laber>').appendTo($('#test1'));  //안.마지막에
               $('<laber>prependTo()</laber>').prependTo($('#test2')); //안.앞에 추가
               $('<label>insertBefore()</label>').insertBefore($('#test3'));//a를b앞
              $('<label>insertAfter()</label>').insertAfter($('#test4'))//a를 b뒤
                setTimeout(function(){
                    clearInterval(interval);
                },2000);
            }, 1000)
        });
    </script>

'JQUERY > 함수' 카테고리의 다른 글

요소추가. append, prepend, before, after  (0) 2022.08.28
요소추가. append, prepend, before, after  (0) 2022.08.28
text()/ html()  (0) 2022.08.28
each(), addClass(), toggleCalss()  (0) 2022.08.28
each(), addClass(), toggleCalss()  (0) 2022.08.28

+ Recent posts