Show and hide an element with dynamic IDs on jQuery -


i have several checkboxes on wordpress page id of following format

id = 'more-talktime-{{post.id}} post.id set dynamically.

then have div element id of id = 'talktime-options-{{post.id}}'

what try when clicking on checkbox, show/hide related div element. tried this:

jquery( function ( $ ) {     jquery(document).ready(function(){         jquery('[id^=more-talktime-]').change(function(){             var id = this.id.split('-').pop();                 if(this.checked)                     jquery('#talktime-options-' + id).fadein('slow');                 else                     jquery('#talktime-options-' + id).fadeout('slow');         });     }); }); 

i confirmed var id right one. show/hide doesn't work , don't have error on console.

the div element has display: none default.

edit add html code too:

<div class="col-md-6 add-on-service">     <h3>more talktime</h3>     <input type="checkbox" name="more-talktime" id="more-talktime-{{post.id}}" class="add-on-service-checkbox">     <label for="more-talktime" class="add-on-service-description">blah blah blah</label> </div>  <div class="add-on-service talktime-options hidden-box" id="talktime-options-{{post-id}}">     <h3>choose talktime duration</h3>         ...... </div> 

fixed found problem. div element had typo see on html code , instead of {{post.id}} {{post-id}} dash. such silly mistake. of comments , answers helped me dig more on , find issue.

your code seems work correctly, given following below. if checkboxes , divs dynamically generated id's added dom after page loads, may want utilize following "change" listener..

jquery(function($) {    jquery(document).ready(function() {      jquery(document).on('change', '[id^=more-talktime-]', function() {        var id = this.id.split('-').pop();        if (this.checked)          jquery('#talktime-options-' + id).fadein('slow');        else          jquery('#talktime-options-' + id).fadeout('slow');      });    });  });
.no-display {    display: none;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <label for="more-talktime-1">check 1</label>  <input type="checkbox" id="more-talktime-1" />  <div id="talktime-options-1" class="no-display">div 1</div>  <label for="more-talktime-2">check 2</label>  <input type="checkbox" id="more-talktime-2" />  <div id="talktime-options-2" class="no-display">div 2</div>


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -