Skip to content

Instantly share code, notes, and snippets.

@PluginHive
Last active January 18, 2020 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PluginHive/67c3c63078088f397d453d18a73a69ed to your computer and use it in GitHub Desktop.
Save PluginHive/67c3c63078088f397d453d18a73a69ed to your computer and use it in GitHub Desktop.
Restrict the maximum number of checkbox addon user can select in the frontend
add_action('wp_footer','scripting');
function scripting()
{
?>
<script type="text/javascript">
// console.clear();
// console.log("started check box condition");
jQuery(document).ready(function($){
var max_selection=2; // change this value
jQuery(document).on('click', '.single_add_to_cart_button', function (e) {
// console.log("inside check box condition");
// alert("Start");
jQuery(this).removeClass('loading');
jQuery('.required_checkbox').removeClass('required_checkbox');
jQuery('.required_radiobutton').removeClass('required_radiobutton');
jQuery('.required_addons').removeClass('required_addons');
jQuery('.required_addons').removeClass('colour_options_addons');
var cart_button=this;
var i=0
jQuery('.ph_check_box_addons').each(function(){
current_div=this;
if(jQuery(this).attr('data-required')==1 && !jQuery(this).closest('.ph-addon-container').is(':hidden'))
{
var num_elements_selected = jQuery(this).find('.phive-addon-checkbox:checked').length;
if(num_elements_selected>max_selection || num_elements_selected==0)
{
// jQuery(this).addClass('required_checkbox');
jQuery(this).closest('.ph-addon-container').addClass('required_addons');
// if(jQuery(this).hasClass('loading'))
// {
jQuery(cart_button).removeClass('loading');
// }
i++;
jQuery(current_div).closest('.ph-addon-container').focus();
}
if(num_elements_selected>max_selection)
{
name=jQuery(this).closest('.ph-addon-container').find('label').html();
name=name.replace('<span class="required_star">*</span>',"");
name = name.replace(/\n/g, "");
name = name.replace(/\s\s+/g, ' ');
name = name.replace(/ +/g, ' ');
alert("Maximum allowed selection for "+name+" is "+max_selection);
}
}
});
if(i>0)
{
jQuery('.required_addons').first().focus();
e.preventDefault();
return false;
}
});
});
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment