0

I'm trying to run a simple jQuery function in wordpress to hide and show content depending on a drop-down list, the code works fine outside wordpress, but when I add it to my child theme display all the content. I've checked the header and the jQuery file is loaded properly.

jQuery(document).ready(function() {
    $('#id_BJ').closest('article').addClass('city_table').hide();
    $('#id_SH').closest('article').addClass('city_table').hide();
    $('#id_SZ').closest('article').addClass('city_table').hide();

    $('#id_chinese_city').change(function() {
        $('article.city_table').hide();
        $('#id_' + $(this).val()).closest('article').show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select name="chinese_city" id="id_chinese_city">
<option value="">Choose first</option>
<option value="BJ">Beijing</option>
<option value="SH">Shanghai</option>
<option value="SZ">Shenzhen</option>
</select>
<article id="id_BJ">
    </br>
    <h3>Beijing</h3></article>
<article id="id_SH">
    </br>
    <h3>Shanghai</h3></article>
<article id="id_SZ">
    </br>
    <h3>Shenzhen</h3></article>

I've also tried to using tags but the result is the same

any ideas why this is happening?

  • Is the function in a separate js file? Make sure it is loaded after jQuery is defined. Do you have a link for the live page? – Enkode Sep 15 '15 at 18:28

3 Answers3

1

Change

jQuery(document).ready(function() {

to:

jQuery(document).ready(function($) {

Wordpress runs jQuery in Safe Mode by default. Change the above line and you should be able to use $ within your code as normal.

Another alternative is as follows:

(function($) {
    //Code here
})( jQuery );
Alvin Pascoe
  • 1,189
  • 7
  • 5
0

I think it may be because you are using the $ with jquery in safe mode, what you can do it change your function like this

jQuery(document).ready(function($) {
    $('#id_BJ').closest('article').addClass('city_table').hide();
    $('#id_SH').closest('article').addClass('city_table').hide();
    $('#id_SZ').closest('article').addClass('city_table').hide();

    $('#id_chinese_city').change(function() {
        $('article.city_table').hide();
        $('#id_' + $(this).val()).closest('article').show();
    });
});

and it should allow you to pass the $ and it should make your function work.

Look at my document.ready line vs yours to see what i'm talking about.

Robert430404
  • 425
  • 5
  • 16
0

WordPress uses jQuery in noConflict mode.

Above solutions should work.

However if you take a look on the APPI Doc this should make it more clear - https://api.jquery.com/jquery.noconflict/

mmaumio
  • 117
  • 1
  • 9