phppup Posted October 2, 2023 Share Posted October 2, 2023 Hello all. I had hardcoded if(document.getElementById("Item_01").checked == true){ document.getElementById("Set_01").style.display = "block"; } else { document.getElementById("Set_01").style.display = "none"; } This referenced items in a form that corresponded to values in a PHP array and all seemed to work well. But when I realized that expanding to multiple items in the array would mean manually re-writing these same lines for every item, it occurred to me that writing a single piece of code to engage the array with a FOR LOOP would be more effective (and reduce code). I searched the web and discovered that this could be the answer to incorporate into my function: var array = <?php echo json_encode($business); ?>; I tested at each step to avoid issues, but noticed that while things seemed to work well, they stalled when I refreshed my webpage. Is there a specific way to exit the JSON or disable it so that the page works properly every time (as it does WITHOUT this variable? Should I be using a different approach to connect JavaScript to a PHP array? Quote Link to comment Share on other sites More sharing options...
kicken Posted October 2, 2023 Share Posted October 2, 2023 I have no idea what you mean by exit the JSON, that phrase doesn't make any sense. JSON isn't some running code that you exit out of, it's just a data structure. Dumping an array into a script block as JSON can work, though I generally prefer to dump the json into a data-* attribute and then use JavaScript to extract it, as that is less likely to cause your code to break or leave you open to a XSS attack. You might not have to dump your array into your JavaScript at all if your generating a repeating HTML structure for each array entry. You could just have your JavaScript code work with the structure rather than having to use getElementById with different ID values. In general, IDs are something best avoided if possible, especially for anything where you need multiple instances of it. Quote Link to comment Share on other sites More sharing options...
phppup Posted October 2, 2023 Author Share Posted October 2, 2023 (edited) Quote You could just have your JavaScript code work with the structure rather than having to use getElementById with different ID values. @kicken Not sure what you mean or how to approach this Quote In general, IDs are something best avoided Why? Quote no idea what you mean by exit the JSON Me neither, but I realized that this cause was JSON, and wasn't sure if I had missed an aspect of "special handling" that might be required to neutralize any effects (other than hashtags to remove it... LOL) Edited October 2, 2023 by phppup Quote Link to comment Share on other sites More sharing options...
maxxd Posted October 2, 2023 Share Posted October 2, 2023 You'll need to check your errors; you'll see them in the console if it's a JavaScript error or in the HTML source if it's a PHP error. You also need to wrap the PHP code in quotes - JSON is a string and JavaScript expects it to be treated as such. Quote Link to comment Share on other sites More sharing options...
phppup Posted October 2, 2023 Author Share Posted October 2, 2023 @maxxdNot really sure what you mean, but the same code worked fine when run separately with my PHP array. It only displayed a problem when I incorporated it into my form. Quote Link to comment Share on other sites More sharing options...
Solution kicken Posted October 3, 2023 Solution Share Posted October 3, 2023 4 hours ago, phppup said: Not sure what you mean or how to approach this It's a lot like using relative file paths rather than absolute paths in your PHP code or HTML links. Rather than trying to reference everything with an ID and getElementById, you instead reference elements relative to other elements using things like parentElement, nextElementSibling, previousElementSibling, querySelector, etc. You can usually reference some parent element (either by ID or a class name) then locate child elements either via their position in the HTML structure or class names. Without knowing what your HTML is, I can't provide and specific recommendation. Here is an example though: window.addEventListener('DOMContentLoaded', () => { const list = document.getElementById('option-list'); list.addEventListener('change', (e)=>{ const checkbox=e.target; const description=checkbox.parentElement.nextElementSibling; description.style.display=checkbox.checked?'block':'none'; }); }); Paired with the HTML <ul id="option-list"> <li> <label><input type="checkbox"> Test option 1</label> <div class="description">Some description for option 1</div> </li> <li> <label><input type="checkbox"> Test option 2</label> <div class="description">Some description for option 2</div> </li> <li> <label><input type="checkbox"> Test option 3</label> <div class="description">Some description for option 3</div> </li> <li> <label><input type="checkbox"> Test option 4</label> <div class="description">Some description for option 4</div> </li> </ul> The JavaScript code only references the parent list element by and ID and listens for a change event on it (which will be triggered by a change in any child). When that change event is triggered, the input element that triggered it can be references using e.target. Looking at the HTML structure, the div that should be shown/hidden is a sibling to the inputs parent, so a reference to it can be obtained by first getting the input parent (parentElement) then it's next sibling(nextElementSibling). With this code, you can add as many <li> elements following that structure as you want and they will all work. No need to generate unique IDs for each and add custom event handlers to each one. 4 hours ago, phppup said: Why? For exactly the reason you created this thread, and more. ID's must be unique, so if you have some repeating structure you need to find some way of generating unique IDs and reference those IDs in your code. Often times, using class names or other more natural references are better and avoid these issues. Quote Link to comment Share on other sites More sharing options...
phppup Posted October 7, 2023 Author Share Posted October 7, 2023 @kicken I thought I'd share this interesting revelation. While beginning to alter my code to implement your suggested approach I //commented out// some areas of code. That's when I noticed that the color designations on my editing tool were inconsistent. Long story short, it seems my code was stalling because ////var array = <?php echo json_encode($business); ?>; did NOT remove the code, COMPLETELY and in fact created a hiccup until I tried ////var array = <?php /** echo json_encode($business); **/ ?>; Thankfully, now my code is working. PS: had to post on this fashion as the editor would not display the leading backslashes Quote Link to comment Share on other sites More sharing options...
kicken Posted October 8, 2023 Share Posted October 8, 2023 4 hours ago, phppup said: did NOT remove the code, COMPLETELY That is expected. In that code, the //// is a single-line comment in the final JavaScript code, your PHP code is unaffected by that. Your PHP script would end up outputting something like this: ////var array = [ {"some":"json"}, {"more":"json"} ]; Note only the first line is commented, the rest remains live and causes a syntax error. Adding the additional comment in the PHP tags prevents PHP from outputting the JSON value so you end up with the output: ////var array = ; Which is successfully commented out by the single-line JS comment. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.