0

I use a form that display some div depending on which option you click of the radio button.

The thing is that the div is set to be none displayed, except if I select an option.

So I added the following function in order to make sure that if the div is displayed it will have th form havin the required property.

SO I give this function:

<script type="text/javascript">
function addattribute()
{
    if (document.getElementById('montant').style.display == "block")
    {
        document.getElementsByName('montant_creance').setAttribute('required');
        document.getElementsByName('condition2').setAttribute('required');
    }
    if (document.getElementById('montant').style.display == "none")
    {
        document.getElementsByName('montant_creance').setAttribute('required','false');
        document.getElementsByName('condition2').setAttribute('required','false');
    }
}
</script>   

But It say to me in the console:

Uncaught TypeError: Object #<NodeList> has no method 'setAttribute'

I really do not know how to find an issue.

Receive all my utmost Respect.

Kind Regards.

SP.

Yoshi
  • 54,081
  • 14
  • 89
  • 103
Stanislas Piotrowski
  • 2,595
  • 10
  • 40
  • 59

2 Answers2

2

getElementsByName return a collection of elements, so you have to write e.g.

document.getElementsByName('montant_creance')[0].setAttribute('required');

every time you use this method (or similar methods, like getElementsByTagName, getElementsByClassName...) using the right index

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • thanks a lot, I'put what you told me; and now it say to me An invalid form control with name='condition2' is not focusable. – Stanislas Piotrowski Sep 27 '12 at 12:05
  • if you feel this issue is not related with your original question you should open a new discussion and post some code to see in a demo page /fiddle/jsbin otherwise just post a link with some code – Fabrizio Calderan Sep 27 '12 at 12:07
  • in fact it works except that When I click back to the first option and the div is set to not be displayed it show this message. – Stanislas Piotrowski Sep 27 '12 at 12:15
0

the setAttribute takes 2 parameters name and value:

setAttribute('name','value');
AboQutiesh
  • 1,696
  • 2
  • 9
  • 14
  • Dear Sir that is what I wrote setAttribute('required','false'); – Stanislas Piotrowski Sep 27 '12 at 12:02
  • I have this – Stanislas Piotrowski Sep 27 '12 at 12:05
  • – AboQutiesh Sep 27 '12 at 13:00