Skip to content Skip to sidebar Skip to footer

Display A 'div' Box Only When A Specific Checkbox Is Selected

I have the next form in a Wordpress plugin and I want to display the 'div' box with the 'Price' text field only when the checkboxes 'Not free 1' or 'Not free 2' are checked. I know

Solution 1:

I think the options should be radio buttons instead of checkboxes. This code will help you get started:

var advertNodes = $('#advert_category-1, #advert_category-2 ');
var advertInput = $('.adverts-field-text');

advertNodes.click(function() {
  if (!advertNodes.is(':checked')) {
    advertInput.hide();
  }
  else {
    advertInput.show(); 
  }
});

Solution 2:

Finally I have arrived to this working solution:

// a form in a plugin (not mine):
<form action="" method="post">
    <fieldset><div><labelfor="category">Categories</label><selectid="category"name="category"><optionvalue="">Select Options ...</option><optionvalue="2">Free</option><optionvalue="4">Not free 1</option><optionvalue="7">Not free 2</option></select></div><div><labelfor="price">Price</label><inputname="price"id="price"type="text"></div></fieldset></form>// another plugin (*display-price.php*) (this is mine)add_action( 'wp_enqueue_scripts', 'add_my_script' );
functionadd_my_script() {
    wp_enqueue_script(
        'display-price',
        plugins_url( '/display-price.js' , __FILE__ ),
        array('jquery')
    );
}

// a jQuery (*display-price.js*) to display the 'div' box with// the 'Price' text field only when the option 'Not free 1' or// 'Not free 2' are selectedjQuery(document).ready(function($) {

    var cat = ["4", "7"]; // option values for which the price field is displayed
    $("#price").parent('div').hide();

    $('#category').change(function(){
        if($.inArray($('#category').val(), cat) > -1) {
            $("#price").parent('div').show(); 
        } else {
            $("#price").parent('div').hide(); 
        } 
    });
});

Both display-price.php and display-price.js files are located in the same directory (the default Wordpress plugins directory).

Post a Comment for "Display A 'div' Box Only When A Specific Checkbox Is Selected"