How to check whether checkbox element is checked or not by ID/name in Javascript?

You can check whether a given checkbox field is checked or not with Javascript by querySelector or getElementById method.

There are lots of ways to fetch Checked element results by native javascript.

Let’s give a code snippet for the Checkbox Element,

<div class="field choice">
    <input type="checkbox" name="show-password" title="Show Password" id="show-password" class="checkbox">
    <label for="show-password" class="label">Show Password</label>
</div>
  • Checkbox Element checked with querySelector method,
    let showPasswordField = document.querySelector("input[name=show-password]"); // BY Name Attribute
    let showPasswordField = document.querySelector("#show-password"); //By ID
    if (showPasswordField) {
     let result = showPasswordField.checked;
     console.log(result);
    }
  • To Get Results by id attribute,
let showPasswordField = document.getElementById("show-password");
if (showPasswordField) {
    let isChecked = showPasswordField.checked;
    console.log(isChecked);
}
  • To Get Results by name attribute,
    Here Checkbox field name attribute value is “show-password”,
let showPasswordField = document.getElementsByName("show-password");
if (showPasswordField.length !== 0) {
    let isChecked = showPasswordField[0].checked;
    console.log(isChecked);
}
  • Using jQuery
$("#show-password").is(':checked')

How to resolved Uncaught SyntaxError: Unexpected token ‘ in JSON at position 159 in Magento?

While Developing features with Magento and javascript, sometimes you are facing an error in the browser console for the unexpected token defined in JSON and that will break your Magento functionality on that page.

This type of error we are facing is due to tiny mistakes in javascript JSON Declaration in our code.

This error is coming because our javascript snippet declaration using script text x-magento-init syntax has minor mistakes. Continue reading “How to resolved Uncaught SyntaxError: Unexpected token ‘ in JSON at position 159 in Magento?”

How to add custom validation rule in javascript using magento 2?

You can add a new validation rule with the data-validate attribute of the HTML tag using Magento.

By Default Magento mage/validation.js file used to set out-of-the-box custom rules for the Magento. Most of the times custom rules are used in the input tags. though you can apply to form tag, select tag as well as any HTML tag.

Syntax:
$.validator.addMethod(argument1, argument2, argument3) used to define custom validation rule in Magento. Continue reading “How to add custom validation rule in javascript using magento 2?”