index6.html:406 Uncaught TypeError: Cannot read properties of null (reading 'checked')
    at index6.html:406:67
    at Array.map (<anonymous>)
    at addNewRecord (index6.html:404:58)
    at HTMLButtonElement.onclick (index6.html:259:58)
(anonymous)	@	index6.html:406
addNewRecord	@	index6.html:404
onclick	@	index6.html:259

for the following code, which is scraping tool, each row has name, selector and one more attribute associated with a switch to determine if field should apply selector or regex to the fetch html. kindly fix the logic:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Scraping Tool</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #e0e0e0;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            flex-direction: column;
            min-height: 100vh;
            width: 100%;
            box-sizing: border-box;
        }

        h1 {
            color: #333;
            text-align: center;
            width: 100%;
            margin: 20px 0;
        }

        .table-container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            background-color: #e0e0e0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
            border-radius: 12px;
            overflow: hidden;
        }

        th,
        td {
            padding: 12px;
            text-align: left;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            vertical-align: top;
        }

        th {
            background-color: #e0e0e0;
            box-shadow: inset 1px 1px 2px #d1d1d1, inset -1px -1px 2px #ffffff;
            color: #555;
        }

        td {
            background-color: #e0e0e0;
            color: #333;
        }

        input[type="text"] {
            width: calc(100% - 16px);
            padding: 8px;
            border: none;
            border-radius: 8px;
            box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
            background-color: #e0e0e0;
            margin: 5px 0;
        }

        button {
            padding: 10px 15px;
            border: none;
            border-radius: 8px;
            background-color: #e0e0e0;
            box-shadow: 5px 5px 10px #bebebe, -5px -5px 10px #ffffff;
            cursor: pointer;
            font-size: 14px;
            margin-right: 5px;
        }

        button:hover {
            box-shadow: inset 2px 2px 5px #bebebe, inset -2px -2px 5px #ffffff;
        }

        .debug-panel,
        .result-panel {
            position: fixed;
            top: 8%;
            left: 50%;
            transform: translateX(-50%);
            width: 80%;
            max-height: 400px;
            overflow-y: auto;
            background-color: #e0e0e0;
            box-shadow: 8px 8px 20px #bebebe, -8px -8px 20px #ffffff;
            border-radius: 10px;
            padding: 20px;
            display: none;
            z-index: 1000;
        }

        .close-btn {
            float: right;
            cursor: pointer;
            font-weight: bold;
            color: #333;
        }

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.3);
            display: none;
            z-index: 999;
        }

        .auto-fetch-switch-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .switch-label-container {
            display: flex;
            align-items: center;
        }

        .auto-fetch-switch-label {
            margin-right: 10px;
            color: #333;
            font-weight: bold;
        }

        .auto-fetch-switch,
        .regex-switch {
            position: relative;
            display: inline-block;
            width: 48px;
            height: 22px;
            margin: 10px 0;
        }

        .auto-fetch-switch input,
        .regex-switch input {
            display: none;
        }

        .switch {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 22px;
        }

        .switch:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked+.switch {
            background-color: #2196f3;
        }

        input:checked+.switch:before {
            transform: translateX(26px);
        }

        .request-access-link {
            color: #2196F3;
            font-weight: bold;
            text-decoration: none;
        }

        .result-link {
            color: #2196F3;
            cursor: pointer;
            text-decoration: underline;
        }

        .selector-field {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .selector-field input[type='text'] {
            flex: 1;
            margin-right: 5px;
        }
    </style>
</head>

<body>

    <h1>Web Scraping Tool</h1>
    <div class="table-container">
        <div class="auto-fetch-switch-container">
            <div class="switch-label-container">
                <span class="auto-fetch-switch-label">Auto Fetch on Load</span>
                <label class="auto-fetch-switch">
                    <input type="checkbox" id="auto-fetch-switch" onchange="toggleAutoFetch(this.checked)">
                    <span class="switch"></span>
                </label>
            </div>
            <a href="https://cors-anywhere.herokuapp.com/corsdemo" class="request-access-link" target="_blank">Not working? Request access here</a>
        </div>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>URL</th>
                    <th>Selectors/Regex</th>
                    <th>Use regex?</th>
                    <th>Results</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="scrape-table-body">
                <tr>
                    <td><input type="text" id="new-name" placeholder="Enter name"></td>
                    <td><input type="text" id="new-url" placeholder="Enter URL"></td>
                    <td>
                        <div class="selector-container" id="new-selector-container">
                            <div class="selector-field">
                                <input type="text" id="new-selector-0" placeholder="Enter Selector or Regex">
                                <button onclick="addSelectorField('new-selector-container', 'new-regex-container')">+</button>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="regex-switch-container" id="new-regex-container">
                            <label class="regex-switch">
                                <input type="checkbox" id="new-regex-0">
                                <span class="switch"></span>
                            </label>
                        </div>
                    </td>
                    <td><button onclick="addNewRecord()">✚</button></td>
                </tr>
            </tbody>
        </table>
    </div>

    <div id="overlay" class="overlay" onclick="closePanels()"></div>
    <div id="debug-panel" class="debug-panel">
        <span class="close-btn" onclick="toggleDebugPanel(null, true)">×</span>
        <pre id="debug-content"></pre>
    </div>
    <div id="result-panel" class="result-panel">
        <span class="close-btn" onclick="toggleResultPanel(null, true)">×</span>
        <pre id="result-content"></pre>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        const recordsKey = 'scrapeRecords';
        const autoFetchKey = 'autoFetch';
        const maxResultLength = 50;

        document.addEventListener('DOMContentLoaded', () => {
            const autoFetchState = localStorage.getItem(autoFetchKey);
            const autoFetch = (autoFetchState === 'true');
            const autoFetchSwitch = document.getElementById('auto-fetch-switch');
            autoFetchSwitch.checked = autoFetch;
            loadRecords(autoFetch);
        });

        function toggleAutoFetch(isEnabled) {
            localStorage.setItem(autoFetchKey, isEnabled);
            if (isEnabled) {
                executeAllRecords();
            }
        }

        function loadRecords(autoFetch) {
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records.forEach((record, index) => {
                addTableRow(record, index);
                if (autoFetch) {
                    executeRecord(index);
                }
            });
        }

        function addTableRow({ name, url, selectors }, index) {
            const tableBody = document.getElementById('scrape-table-body');
            const row = document.createElement('tr');

            row.innerHTML = `
                <td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
                <td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
                <td>
                    <div id="selector-container-${index}" class="selector-container"></div>
                </td>
                <td>
                    <div id="regex-container-${index}" class="regex-switch-container"></div>
                </td>
                <td id="result-${index}"></td>
                <td>
                    <button onclick="executeRecord(${index})">▶️</button>
                    <button onclick="removeRecord(${index})">🗑️</button>
                    <button onclick="toggleDebugPanel(${index}, false)">ℹ️</button>
                </td>
            `;

            tableBody.insertBefore(row, tableBody.lastElementChild);

            selectors.forEach((selector, sIndex) => {
                addSelectorField(`selector-container-${index}`, `regex-container-${index}`, selector.value, selector.isRegex);
            });

            updateAddRemoveButtons(`selector-container-${index}`, `regex-container-${index}`);
        }

        function addSelectorField(selectorContainerId, regexContainerId, value = '', isRegex = false) {
            const selectorContainer = document.getElementById(selectorContainerId);
            const regexContainer = document.getElementById(regexContainerId);

            const fieldDiv = document.createElement('div');
            fieldDiv.className = 'selector-field';
            fieldDiv.innerHTML = `
                <input type="text" value="${escapeHtml(value)}" placeholder="Enter Selector or Regex">
            `;
            selectorContainer.appendChild(fieldDiv);

            const switchDiv = document.createElement('div');
            switchDiv.className = 'selector-field';
            switchDiv.innerHTML = `
                <label class="regex-switch">
                    <input type="checkbox" ${isRegex ? 'checked' : ''}>
                    <span class="switch"></span>
                </label>
            `;
            regexContainer.appendChild(switchDiv);

            updateAddRemoveButtons(selectorContainerId, regexContainerId);
        }

        function updateAddRemoveButtons(selectorContainerId, regexContainerId) {
            const selectorContainer = document.getElementById(selectorContainerId);
            const selectors = selectorContainer.querySelectorAll('.selector-field');
            const regexContainer = document.getElementById(regexContainerId);
            const regexSwitches = regexContainer.querySelectorAll('.selector-field');

            selectors.forEach((field, index) => {
                const existingButtons = field.querySelectorAll('button');
                existingButtons.forEach(button => button.remove());

                const addButton = document.createElement('button');
                addButton.textContent = '+';
                addButton.onclick = function () {
                    addSelectorField(selectorContainerId, regexContainerId);
                };

                if (index === selectors.length - 1) {
                    field.appendChild(addButton);
                }

                if (selectors.length > 1) {
                    const removeButton = document.createElement('button');
                    removeButton.textContent = '-';
                    removeButton.onclick = function () {
                        selectorContainer.removeChild(field);
                        regexContainer.removeChild(regexSwitches[index]);
                        updateAddRemoveButtons(selectorContainerId, regexContainerId);
                    };
                    field.appendChild(removeButton);
                }
            });
        }

        function checkEnter(event, index) {
            if (event.key === 'Enter') {
                executeRecord(index);
            }
        }

        function addNewRecord() {
            const name = document.getElementById('new-name').value;
            const url = document.getElementById('new-url').value;

            const selectorFields = document.querySelectorAll('#new-selector-container .selector-field');
            const selectors = Array.from(selectorFields).map((field, i) => ({
                value: field.querySelector('input[type="text"]').value,
                isRegex: document.getElementById(`new-regex-${i}`).checked
            }));

            if (!name || !url || selectors.every(sel => !sel.value)) {
                alert('All fields are required!');
                return;
            }

            const record = { name, url, selectors, response: '', timestamp: '' };
            let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records.push(record);
            localStorage.setItem(recordsKey, JSON.stringify(records));

            const index = records.length - 1;
            addTableRow(record, index);
            executeRecord(index);

            document.getElementById('new-name').value = '';
            document.getElementById('new-url').value = '';
            selectorFields.forEach(field => {
                field.querySelector('input[type="text"]').value = '';
                field.querySelector('input[type="checkbox"]').checked = false;
            });
        }

        function executeRecord(index) {
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            const { url, selectors } = records[index];
            document.getElementById(`result-${index}`).textContent = '⏳';
            executeScraping(url, selectors, index);
        }

        function executeScraping(url, selectors, index) {
            const proxy = 'https://cors-anywhere.herokuapp.com/';
            const options = {
                headers: {
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'Accept-Language': 'en-US,en;q=0.9'
                }
            };

            axios.get(proxy + url, options)
                .then(response => {
                    const results = selectors.map(selectorObj => {
                        const { value, isRegex } = selectorObj;
                        let resultText = 'No matches';
                        if (isRegex) {
                            try {
                                const regex = new RegExp(value);
                                const match = regex.exec(response.data);
                                resultText = match ? match[0] : 'No matches';
                            } catch (e) {
                                console.error('Invalid regex:', e);
                                resultText = 'Invalid regex';
                            }
                        } else {
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(response.data, 'text/html');
                            const resultElement = doc.querySelector(value);
                            resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
                        }
                        return resultText;
                    });

                    const timestamp = new Date().toISOString();
                    updateResult(index, response.data, timestamp, results);
                })
                .catch(error => {
                    console.error(`Error fetching the URL: ${url}`, error);
                    const timestamp = new Date().toISOString();
                    updateResult(index, `Error: ${error.message}`, timestamp, ['Error occurred']);
                });
        }

        function updateResult(index, response, timestamp, results) {
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records[index].response = response;
            records[index].timestamp = timestamp;
            localStorage.setItem(recordsKey, JSON.stringify(records));

            const resultContainer = document.createElement('div');
            results.forEach(resultText => {
                let displayResult = resultText;
                if (resultText.length > maxResultLength) {
                    displayResult = `${resultText.substring(0, maxResultLength)}... <span class="result-link" onclick="toggleResultPanel(${index}, false)">Read more</span>`;
                }

                const resultElement = document.createElement('div');
                resultElement.innerHTML = displayResult;
                resultContainer.appendChild(resultElement);
            });

            const resultCell = document.getElementById(`result-${index}`);
            resultCell.innerHTML = '';
            resultCell.appendChild(resultContainer);
        }

        function updateRecord(index, field, value) {
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records[index][field] = value;
            localStorage.setItem(recordsKey, JSON.stringify(records));
        }

        function removeRecord(index) {
            let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records.splice(index, 1);
            localStorage.setItem(recordsKey, JSON.stringify(records));
            document.location.reload();
        }

        function toggleDebugPanel(index, close = false) {
            const debugPanel = document.getElementById('debug-panel');
            const debugContent = document.getElementById('debug-content');
            const overlay = document.getElementById('overlay');
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];

            if (close || index === null) {
                debugPanel.style.display = 'none';
                overlay.style.display = 'none';
                debugContent.textContent = '';
                return;
            }

            const timestamp = records[index].timestamp || 'No timestamp';
            const response = records[index].response || 'No response';
            const debugText = `Timestamp: ${timestamp}\n\nRaw Response:\n${response}`;
            debugPanel.style.display = 'block';
            overlay.style.display = 'block';
            debugContent.textContent = debugText;
        }

        function toggleResultPanel(index, close = false) {
            const resultPanel = document.getElementById('result-panel');
            const resultContent = document.getElementById('result-content');
            const overlay = document.getElementById('overlay');
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];

            if (close || index === null) {
                resultPanel.style.display = 'none';
                overlay.style.display = 'none';
                resultContent.textContent = '';
                return;
            }

            const resultText = records[index].response || 'No Result Data';
            resultPanel.style.display = 'block';
            overlay.style.display = 'block';
            resultContent.textContent = resultText;
        }

        function closePanels() {
            toggleDebugPanel(null, true);
            toggleResultPanel(null, true);
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, function (m) { return map[m]; });
        }

        function executeAllRecords() {
            const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
            records.forEach((_, index) => {
                executeRecord(index);
            });
        }
    </script>
</body>
</html>