'Conditionally make field optional based on selected state - Woocommerce(NOT RESOLVED) [duplicate]
I’ve been trying for a while now to find a solution to this issue I am facing, that being that I desire to condition the billing_city field in checkout to be optional while hidden only when the customer selects a certain state from the drop-down menu.
This is the code I’ve used to achieve the conditional hidding/showing, but it doesnt make the field unrequired, thus making it impossible to place an order.
add_action( 'wp_footer', 'conditionally_hidding_billing_city' );
function conditionally_hidding_billing_city() {
// Only on checkout page
if ( !is_checkout() )
return;
?>
<script>
jQuery(function($){
// Choosen billing state selectors slug
//var billingState = '#billing_state',
// Function that shows or hide input select fields
var billingState = $('#billing_state').val();
// Initialising: Hide if chosen billing_state is "BS"
if( billingState == 'BS1' || billingState == 'BS2' || billingState == 'BS3' || billingState == 'BS4' || billingState == 'BS5' || billingState == 'BS6' )
showHide('hide','#billing_city' );
// Live event (When billing state is changed)
$( '#billing_state' ).on( 'change', function() {
var billingState = $('#billing_state').val();
if( billingState == 'BS1' || billingState == 'BS2' || billingState == 'BS3' || billingState == 'BS4' || billingState == 'BS5' || billingState == 'BS6' )
{
showHide('hide','#billing_city');
$('label[for="billing_city"]').hide();
}
else{
showHide('show','#billing_city');
$('label[for="billing_city"]').show();
}
});
function showHide( actionToDo='show', selector='' ){
if( actionToDo == 'show' )
$(selector).show( 200, function(){
$(this).addClass("validate-required");
});
else
$(selector).hide( 200, function(){
$(this).removeClass("validate-required");
});
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
});
</script>
<?php
}
As far as I was able to understand, this code only removes the class, but doesnt really make it dissapear, which is why it still triggers the required warning.
I would really appreciate a solution as to what exactly would I need to change in order for it to work.
Thanks a lot, waiting for an answer.
Solution 1:[1]
To Remove 'required'
$('#billing_city').removeAttr('required');?????
To add 'required'
$("#billing_city").prop('required',true);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Colin Gell |
