JavaScript Practical Techniques and Code Snippets

Equality Operators in JavaScript

JavaScript provides two sets of comparison operators:

Oeprator Description
== Loose equality (type coercion)
=== Strict equality (no type coercion)
!= Loose inequality
!== Strict inequality
// Loose equality examples
console.log(5 == '5');  // true
console.log(true == 1); // true

// Strict equality examples
console.log(5 === '5');  // false
console.log(true === 1); // false

Using return in JavaScript

The return statement ends function execution and optionally passes a value back to the caller:

function add(a, b) {
    return a + b;
}

function validateInput(value) {
    if (value === null) {
        return false; // Early exit
    }
    // Continue validation
    return true;
}

Select Multiple Choice Dropdown Auto-Close Issue

When a multi-select dropdown closes immediately after the first selection, prevent event propagation:

onchange="event.stopPropagation();"

Alternatively, add this CSS to fix spacing issues:

.am-tabs-nav > li > a {
    margin-bottom: -2px;
}

Copying Table Content

This function extracts table content from an iframe and copies it to clipboard:

function copyTableContent(targetId) {
    const frame = document.getElementById(targetId);
    const frameDoc = frame.contentWindow.document;
    
    let content = frameDoc.documentElement.innerHTML
        .replace(/<td ondblclick="[^"]*"/g, '<td')
        .replace(/<input id="test"[^>]*>/g, '')
        .replace(/<style>[\s\S]*?<\/style>/g, '');

    if (content === '<head></head><body></body>') {
        content = ' ';
    }

    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    textarea.select();

    try {
        document.execCommand('copy');
        console.log('Content copied to clipboard');
    } catch (err) {
        console.error('Copy failed', err);
    } finally {
        document.body.removeChild(textarea);
    }
}

Form Data Serialization

Two methods to serialize form data:

// Returns array of objects
const formDataArray = $('#myForm').serializeArray();

// Returns URL-encoded string
const formDataString = $('#myForm').serialize();

Get selected text from a multi-select dropdown:

const selectedTexts = $('#projectSelect')
    .find('option:selected')
    .map(function() {
        return $(this).text();
    })
    .get();

const joinedText = selectedTexts.join(',');

Array Cloning in JavaScript

Problem: Direct assignment creates a reference, not a copy.

// This creates a reference, not a clone
const original = [1, 2, 3];
const backup = original;
backup.splice(0, 1);
console.log(original); // [2, 3] - original is modified!

Solution: Use slice() to create a shallow copy.

const original = [1, 2, 3];
const backup = original.slice(); // Creates a true copy
backup.splice(0, 1);
console.log(original); // [1, 2, 3] - original unchanged

Understanding offsetTop and offsetLeft

offsetTop returns the vertical distance between the element and its offsetParent element. The offsetParent is the nearest ancestor with CSS positioning applied.

Setting element position with style.left may not work in all cases. Use jQuery's offset method instead:

$('#elementId').offset({ top: 100, left: 100 });

Custom Confirmation Dialog with Callback

Create a modal confirmation dialog that executes a callback function:

window.showConfirmDialog = function(message, callback, confirmText = 'OK') {
    $('#dialogOverlay').remove();
    
    const overlay = document.createElement('div');
    overlay.id = 'dialogOverlay';
    overlay.style.cssText = `
        position: absolute;
        left: 50%;
        top: 50%;
        width: 600px;
        height: 400px;
        margin-left: -300px;
        margin-top: -150px;
        z-index: 1125;
    `;

    const dialog = document.createElement('div');
    dialog.id = 'dialogBox';
    dialog.style.cssText = `
        position: absolute;
        width: 600px;
        height: 400px;
        left: 50%;
        top: 50%;
        margin-left: -300px;
        margin-top: -150px;
        text-align: center;
        z-index: 1130;
    `;

    dialog.innerHTML = `
        <ul style="list-style: none; margin: 0; padding: 0;">
            <li style="background: #bf2126; padding-left: 20px; font-weight: bold; color: white;"></li>
            <li style="padding: 40px; color: #bf2126; font-size: 17px;">${message}</li>
            <li style="padding: 20px;">
                <button id="confirmBtn" style="width: 80px; height: 30px; background: #bf2126; color: white; margin-right: 10px;">${confirmText}</button>
                <button id="cancelBtn" style="width: 80px; height: 30px; background: #ffebef; color: #bf2126;">Cancel</button>
            </li>
        </ul>
    `;

    document.body.appendChild(dialog);
    document.body.appendChild(overlay);

    document.getElementById('confirmBtn').addEventListener('click', () => {
        document.body.removeChild(dialog);
        document.body.removeChild(overlay);
        callback(true);
    });

    document.getElementById('cancelBtn').addEventListener('click', () => {
        document.body.removeChild(dialog);
        document.body.removeChild(overlay);
        callback(false);
    });
};

// Usage
showConfirmDialog('This action cannot be undone!', (confirmed) => {
    if (!confirmed) {
        return;
    }
    // Proceed with action
});

File Download with Page Refresh

Download a file and refresh the page while preserving scroll position:

function downloadWithRefresh(downloadUrl) {
    const currentUrl = location.href;
    
    $.ajaxSettings.async = false; // Synchronous request
    location.href = downloadUrl;
    
    setTimeout(() => {
        location.href = currentUrl;
    }, 800);
}

function delay(ms) {
    const start = Date.now();
    while (Date.now() - start < ms) {
        // Busy wait
    }
}

Preserving Scroll Position After Page Refresh

Maintain scroll position when a page refreshes:

let savedPosition = 0;
let scrollTarget = parseInt(pageScrollParam) || 1; // Default to top

function saveScrollPosition(element) {
    savedPosition = $(element).scrollTop();
    setCookie('scrollPos', savedPosition);
}

window.onload = function() {
    if (!window.name) {
        window.name = 'refreshed';
    } else if (scrollTarget !== 1) {
        $('#contentContainer')[0].scrollTop = getCookie('scrollPos');
        
        // Remove scroll parameter from URL
        const url = window.location.href;
        const paramIndex = url.indexOf('/page_top');
        if (paramIndex > -1) {
            const cleanUrl = url.substring(0, paramIndex);
            history.pushState(null, null, cleanUrl);
        }
    }
};

// Save scroll position on scroll
$('#contentContainer').on('scroll', function() {
    saveScrollPosition(this);
});

Update URL with scroll position after form submission:

location.href = currentUrl.split('/page_top')[0] + '/page_top/' + savedPosition;

Backend should pass page_top parameter to the page.

Double-Click to Copy Text

Enable double-click copy functionality on table cells:

function enableDoubleClickCopy() {
    $('.data-cell').on('dblclick', function() {
        copyToClipboard($(this).text());
    });
}

function copyToClipboard(text) {
    if (!text) return;
    
    const tempInput = document.createElement('input');
    tempInput.value = text;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand('copy');
    tempInput.remove();
    alert('Copied: ' + text);
}

Alternative approach using native event binding:

document.getElementById('copyTarget').addEventListener('dblclick', function() {
    copyToClipboard(this.textContent);
});

jQuery find() vs filter()

Method Description Scope
find() Searches descendants Children, grandchildren, etc.
filter() Filters current collection The selected elements themselves
// find() - searches within selected elements
$('#container').find('.child-item');

// filter() - reduces current selection
$('.item').filter('.active');

Table Row Hover Styling

When using am-table-hover, hidden white icons become visible on hover. Hide them:

tr:hover td[color="white"] {
    color: #e9e9e9;
}

Update URL Without Page Refresh

Use History API to change URL without navigation:

function updateUrlWithoutReload() {
    const currentUrl = window.location.href;
    const hashIndex = currentUrl.indexOf('#');
    
    let cleanUrl = currentUrl;
    if (hashIndex > -1) {
        cleanUrl = currentUrl.substring(0, hashIndex);
    }
    
    history.pushState(null, null, cleanUrl);
}

Back-to-Top Button

.back-to-top {
    box-sizing: border-box;
    display: inline-block;
    width: 48px;
    height: 48px;
    font-size: 18px;
    font-weight: bold;
    line-height: 48px;
    border-radius: 50%;
    background: #eee;
    color: #555;
    text-align: center;
    cursor: pointer;
}
<div style="position: fixed; left: 90%; top: 90%;">
    <a href="#top" class="back-to-top">Top</a>
</div>

Making Checkbox Read-Only

Two methods to prevent checkbox modification:

$('#myCheckbox').prop('readonly', true);
// or
$('#myCheckbox').attr('readonly', true);

CSS Font Weight

/* Common weight values */
font-weight: normal;    /* 400 */
font-weight: bold;      /* 700 */
font-weight: 600;      /* Numeric values: 100-900 */

HTML alternatives: <b> or <strong> tags.

Positive Integer Validation

function isPositiveInteger(value) {
    const pattern = /^[1-9]\d*$/;
    return pattern.test(value);
}

Common regex patterns for numbers:

/^\d+$/           // Non-negative integers (including zero)
/^[0-9]*[1-9][0-9]*$/ // Positive integers
/^((-\d+)|0)$/   // Non-positive integers
/^-[0-9]*[1-9][0-9]*$/ // Negative integers
/^-?\d+$/        // All integers
/^\d+(\.\d+)?$/  // Non-negative decimals
/^[1-9][0-9]*([.][0-9]{1,2})?$/ // Number with up to 2 decimal places

Download Excel Without Page Refresh

function postDownload(url, params, target = '') {
    const form = document.createElement('form');
    form.action = url;
    form.method = 'post';
    form.target = target;
    form.style.display = 'none';

    params.forEach(param => {
        const input = document.createElement('input');
        input.name = param.name;
        input.value = param.value;
        form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

function exportData() {
    if (!$('#productInput').val()) {
        alert('Product is required');
        return false;
    }
    
    const formData = $('#dataForm').serializeArray();
    postDownload('/Admin/Export/excel', formData);
}

Select Dropdown Display Issues

If select dropdowns in tables don't display properly, try setting a default value in the options:

<select>
    <option value="" selected>Select...</option>
    <option value="1">Option 1</option>
</select>

Date Calculations

Calculate a date N days from now:

function addDays(dateString, days) {
    const startDate = new Date(dateString);
    const endDate = new Date(startDate.getTime() + days * 24 * 60 * 60 * 1000);
    return formatDate(endDate);
}

// Usage
const endDate = addDays($('#endDate').val(), 7);
$('#result').val(endDate);

Percentage Calculations

// Convert string to number
const num = Number('0.5');  // 0.5

// String to integer (returns 0 for decimal values)
const intValue = parseInt('0.5');  // 0

// Calculate percentage
const percentage = ((correct / total) * 100).toFixed(2) + '%';

Input Button with Link Behavior

<input type="button" 
       onclick="openReleasePage()" 
       readonly 
       class="btn btn-default"
       value="Open Link">

Getting Uploaded Filename

const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0]; // First file
const fileName = file.name;      // Filename without path

Note: Due to browser security, the full local path is not accessible.

Getting Actual Element Width

// Method 1: getComputedStyle (returns string with 'px')
const widthStr = getComputedStyle(element).width;

// Method 2: getBoundingClientRect (returns number)
const widthNum = element.getBoundingClientRect().width;

The getBoundingClientRect() method provides precise measurements:

// Accurate width measurement
const actualWidth = document.getElementById('myElement').getBoundingClientRect().width;

// Set width using jQuery
$('#myElement').css('width', '500px');

The with Statement

The with statement extends the scope chain for a block:

const config = {
    host: 'localhost',
    port: 8080,
    protocol: 'http'
};

with (config) {
    console.log(host);        // config.host
    console.log(port);        // config.port
    console.log(protocol);    // config.protocol
}

Note: with is not recommended due to readability and performance concerns.

Hex and Percentage Validation

// Validate hex color
const hexPattern = /^#[0-9A-Fa-f]{6}$/;

// Validate percentage
const percentPattern = /^\d+(\.\d+)?%$/;

// Add percentages
function addPercentages(val1, val2) {
    return (parseFloat(val1) + parseFloat(val2)) + '%';
}

Select Triggers Twice Issue

Both trigger() and data-am-validator may fire events twice. Check your event bindings and validation configuration to avoid duplicate execution.

Text Overflow Ellipsis Detection

.truncate {
    width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

Check if text is truncated:

function isTextTruncated(elementId) {
    const el = document.getElementById(elementId);
    return el.clientWidth < el.scrollWidth;
}

For table cells, add table-layout: fixed:

table {
    table-layout: fixed;
}

Form Action Considerations

Two approaches for form action:

<form action="/submit" method="post">
    <!-- Relative paths may cause issues -->
</form>

Use URL helpers for correct paths:

<form action="/Admin/Controller/action" method="post">
    <!-- Absolute paths from root -->
</form>

Button Click Handler in Form

If button's onclick doesn't fire inside a form, the issue is the button type:

Problem: Default type is submit, which submits the form.

Solution: Explicitly set type="button":

<form action="/submit">
    <button onclick="handleClick()" type="button">Click Me</button>
</form>

Passing this to Function

<input onkeyup="getInputValue(this)" />
function getInputValue(inputElement) {
    console.log(inputElement);
    console.log(inputElement.value);
}

DOM and jQuery Object Conversion

jQuery to DOM:

// Method 1: Array index notation
const domElement = $('#selector')[0];

// Method 2: get() method
const domElement = $('#selector').get(0);

DOM to jQuery:

const jqObject = $(domElement);

Removing Elements from Array

Using splice() on an array clone to avoid modifying the original:

const sourceArray = ['a', 'b', '500000A5', 'c'];
const itemsToRemove = ['500000A5'];

const filteredArray = sourceArray.filter(item => !itemsToRemove.includes(item));

Dynamic Required Attribute

Toggle required attribute based on cnoditions:

function toggleRequired(fieldId, isRequired) {
    const field = $('#' + fieldId);
    if (isRequired) {
        field.attr('required', true);
    } else {
        field.removeAttr('required');
    }
}

// Usage
if ($('#modeSelect').val() === 'Yes') {
    toggleRequired('formatA', false);
    toggleRequired('formatB', true);
}

Bulk operations on form fields:

// Add required to multiple fields
$('#section input[type="text"], #section select').each(function() {
    $(this).attr('required', true);
});

// Remove required from multiple fields
$('#section input[type="text"], #section select').each(function() {
    $(this).removeAttr('required');
});

Dynamic Readonly/Disabled States

// Readonly text input
$('input').attr('readonly', 'readonly');

// Disable select
$('select').prop('disabled', true);

// Disable button
$('button.action-btn').attr('disabled', 'disabled');

// Re-enable select
$('select').prop('disabled', false);

// Style disabled select dropdown
$('select').next().css('width', '100%');

Remove opacity effect on disabled select button:

$('#selectElement').next().find('button i').removeClass('opacity-half');

Tags: javascript jquery DOM form Validation

Posted on Wed, 23 Sep 2026 16:14:50 +0000 by terry1989