Pergunta

I need to hide a button until a check box is clicked, however I am stepping into someone elses code who used tag libraries that did not define ID in the button tag. Here is what I have:

The button code:

<html:button name="Next" value="BTN.NEXT" styleClass="button" localeCd="<%= localeCd %>" onClick='Submit("Next")'/>

The checkbox code:

<input type="checkbox" name="fedCheck" onclick="checkFed(this, 'myNext')" value="y" />

The Javascript Code

function checkFed(ele, id) {
x = document.getElementById(id);
if (ele.checked == true) x.disabled = false;
else x.disabled = true;

}

I can get this to work in a seperate page but the page that it is on does not allow for the button to have an ID so it crashes every time. Any suggestions?

Foi útil?

Solução

There would be better ways of doing this, listening for the click event, etc... but, to simply modify your code see this jsFiddle (note: this assumes this is the only element named "Next"):

function checkFed(ele, name) {
    x = document.getElementsByName(name)[0];
    x.disabled = !x.disabled
}

And change the onclick="checkFed(this, 'myNext')" to:

onclick="checkFed(this, 'Next')"

And add disabled="true" to the button so that it's initial state is disabled

...also note that this doesn't actually hide it like the title asks, it disables it, like the content of the question seems to ask.

Outras dicas

Instead of finding the button using document.getElementById, use document.querySelector.

For example, if you have a single button on the page with "Next" as the value of its name attribute:

document.querySelector('button[name="Next"]')
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top