Pergunta

does anyone know why this simple javascript isn't working? it should change the css of the class "t1" from display:none to display: inline to make it appear when the input is empty onSubmit

I just can't understand why it doesnt work?

Thank you so much if your can find where the problem is (btw i want to keep this in pure javascript)

Javascript:

function validate () {

if( document.quote.firstname.value == "" )

{document.getElementByClassName('t1').style = 'display: inline;';
   }

}   

HTML:

<form name="quote" method="post" action="" onSubmit="validate();">

<fieldset>
<legend>Contact Information</legend>

<div>
<label>*First Name:</label><span class="t1">Please enter your name</span>
<input name="firstname" type="text"/>
</div>

</fieldset>

<div id="f-submit">
<input name="Submit" value="Submit" type="submit"/>
</div>

</form>

CSS:

.t1{
display: none;
font-size:13px;
color: #F33;
text-align: right;
}   
Foi útil?

Solução

Suggestion 1: Put ID attributes in the tags so you can access them easier

Suggestion 2: Make the onsubmit attribute be onsubmit="return validate()"

Suggestion 3: getElementByClassName doesn't exist. getElementsByClassName returns an array, so you have to pick which one, or loop through them. IE, document.getElementsByClassName('t1')[0]

Suggestion 4: Your validate function needs to return false if you want the form to not submit, and true if it should submit.

Javascript:

function validate () {

   if( document.getElementById("firstname").value == "" || document.getElementById("firstname").value == null )
    {
    document.getElementsByClassName('t1')[0].setAttribute('style','display: inline;');
    return false;
   }
  return true;
}

HTML:

<form name="quote" method="post" action="" onSubmit="return validate()">

<fieldset>
<legend>Contact Information</legend>

<div>
<label>*First Name:</label><span class="t1">Please enter your name</span>
<input id="firstname" name="firstname" type="text"/>
</div>

</fieldset>

<div id="f-submit">
<input name="Submit" value="Submit" type="submit"/>
</div>

</form>

Outras dicas

There is no document.getElementByClassName. Do you mean, getElementsByClassName? You should also set the display style directly, not through the style attribute. Also, if you need to cancel the form submit, you have to return validate() on the submit, and return false when you want to cancel. I put it in the fiddle as well.

I've made a jsFiddle for you as well: http://jsfiddle.net/rgthree/g4ZvA/2/

<form name="quote" method="post" action="" onSubmit="return validate();">

JS:

function validate () {
  if( document.quote.firstname.value == "" ){
    document.getElementsByClassName('t1')[0].style.display = 'inline';
    return false;  // Return false will cancel the submit, causing the page to not load the form action action
  }
  return true;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top