Trying to hide input element based on json response


What am I doing wrong here? I am trying to hide this <input id="toHide" class="btn btn-primary" value="View" type="button"> element and hence I’ve added an id=toHide and trying to hide it if the value if isViewable is N using the following piece of code in my JSFiddle here

for( var a = 0; a < data.length; a++){

console.log("isViewable length for "+a+" array!");

        for (var b = 0; b < data[a].isViewable.length; b++) {
                if (data[a].isViewable[b] == "N"){
}     }

Not sure if this is the best way to hide the contents in a separate loop as I am doing above or should I do it while building the dynamic table itself? Please advise. Thanks


well for starters i’d recommend you investigate the forEach method, just for some readability aid.

Your primary problem at the moment is that you’re using id=‘toHide’ on a repeated element. You cant have more than one element with the same ID - ID’s are unique.

EDIT: Well i should phrase that better. If you have more than one element with the same ID, browsers will ignore the ID tag of all but the first element with that ID.


Here’s how I might do it.

The view buttons can be accessed as an array-like structure, so put the isVisible information into a similar array-like structure:

const viewable = (category) => category.isViewable;
const merge = (arr, next) => arr.concat(next);
const isViewable =;
// isViewable now contains: ["N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y"]

Then, loop through the buttons toggling them depending on the isViewable information:

const viewButtons = document.querySelectorAll("#populateTable [value=View]");
viewButtons.forEach(function (button, index) {
	$(button).toggle(isViewable[index] === "Y");

A “Y” makes the button visible, and anything else other than a “Y” hides the button.


Thanks very much @Paul_Wilkins . This method reduces the headache of generating dynamic ids (unique ids) for the input element. One question, how’s this thing (category) => category.isViewable; referring to isViewable? I mean, I haven’t used anything like category in my JsFiddle code. Thanks


That is an ES6 feature called an arrow function, which is what I find makes one-liners really easy to understand. An expanded form of that line is:

function isViewable(category) {
    return category.isViewable;

ES6 (also called ES2015) is an updated version of JavaScript with many new features. There’s also ES2016, ES2017 and so on too, with a smaller set of features, but as they are more recent, they are less likely to be supported by currently used browsers.

closed #6

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.