[Day3] JavaScript - Table Input

ShiHoon Yoon·2020년 7월 21일
0

테이블 Width 비율 지정하기

    <table style="width: 100%">
        <colgroup>
            <col span="1" style="width: 20%;">
            <col span="1" style="width: 50%;">
            <col span="1" style="width: 30%;">
        </colgroup>
           

-먼저 테이블 input전에 Width 비율 code를 공유한다.
전체 width 100%로 지정하고 column 갯수를 입력하고 합이 100%로하면 Explorer창 사이즈를 늘리고 줄여도 지정한 비율로 column값이 조정된다.

테이블에 Row 값 추가하기

    <script>
        
        function addRow()
        {
            // get input values
            var fname = document.getElementById('fname').value;
             var lname = document.getElementById('lname').value;
              var age = document.getElementById('age').value;
              
              // get the html table
              // 0 = the first table
              var table = document.getElementsByTagName('table')[0];
              
              // add new empty row to the table
              // 0 = in the top 
              // table.rows.length = the end
              // table.rows.length/2+1 = the center
              var newRow = table.insertRow(table.rows.length/2+1);
              
              // add cells to the row
              var cel1 = newRow.insertCell(0);
              var cel2 = newRow.insertCell(1);
              var cel3 = newRow.insertCell(2);
              
              // add values to the cells
              cel1.innerHTML = fname;
              cel2.innerHTML = lname;
              cel3.innerHTML = age;
        }
        
    </script>

getElement

Document.getElementById() 메서드는 주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 Element 객체를 반환. ID는 문서 내에서 유일해야 하기 때문에 특정 요소를 빠르게 찾을 때 유용.

html 코드

     </head>

<body>
    
    First Name: <input type="text" name="fname" id="fname" /><br/><br/>
    Last Name: <input type="text" name="lname" id="lname" /><br/><br/>
    Age: <input type="text" name="age" id="age" /><br/><br/>
    <button onclick="addRow();">Add Row</button><br/><br/>

    <table border="1">
        
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        
        <tr>
            <td>AAAAAA</td>
            <td>BBBBBB</td>
            <td>10</td>
        </tr>
        
         <tr>
            <td>CCC</td>
            <td>DDDD</td>
            <td>20</td>
        </tr>
        
         <tr>
            <td>EEE</td>
            <td>FFFFF</td>
            <td>30</td>
        </tr>
        
         <tr>
            <td>GGGGG</td>
            <td>HHHH</td>
            <td>40</td>
        </tr>
        
         <tr>
            <td>MMMMMM</td>
            <td>NNNN</td>
            <td>50</td>
        </tr>
        
    </table>

</body>

Run (Outcome)

 
profile
Entrepreneurs Should Learn to Code

0개의 댓글