Skip to content
Advertisement

Show JS alert on a form php

I have the following php code, which is a wordpress hook to display an address autocomplete form on my website’s cart page.

    function add_woocommerce_before_shipping_calculator() {
    $button_text = esc_html( 'Please enter your street & suburb to display available shipping options', 'woocommerce' );
    if (WC()->customer->get_shipping_postcode() != null && WC()->customer->get_shipping_city() != null)
        $button_text = esc_html( 'Not your suburb? Enter a different site', 'woocommerce' );
    $content = '<div>
    <a href="#" class="shipping-calculator-button-auto" style="color: green;" >'.$button_text.'</a>
    <div class="form-row form-row-wide" id="calc_shipping_address_auto_field"> 
    <form class="shipping-calculator-form-auto-form" style="display:block;">
        <input type="text" style="border-color:black; border-style: dashed; padding: 20px;" class="input-text" placeholder="Type your suburb" name="calc_shipping_address_auto" id="calc_shipping_address_auto">
    </form></div>
    </div>';
    echo $content;
}

add_action( 'woocommerce_before_shipping_calculator', 'add_woocommerce_before_shipping_calculator' );

The function was written in functions.php file. I dont want the customer’s to enter their unit numbers or house numbers. As such, I want to display a simple js alert if a customer enters “/” charachter in the input field. What would be the best approach to do this?

Advertisement

Answer

Use HTML attribute: pattern

<form onsubmit="return false;">
<input type="text" style="border-color:black; border-style: dashed; padding: 20px;" class="input-text" placeholder="Type your suburb" name="calc_shipping_address_auto" id="calc_shipping_address_auto" pattern="[^/]*">
<input type="submit">
</form>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement