tags:

views:

44

answers:

4

Greeting, I have this input field <input name="question"/> I want to call IsEmpty function when submit clicking submit button.

I tried the code below but did not work. any advice?!

<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=unicode"/>
    <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator"/>
  </head>
  <body>


    <script language="Javascript">

function IsEmpty(){ 

if(document.form.question.value == "")
{
alert("empty");
}
    return;
}


</script>
Question: <input name="question"/> <br/>

<input id="insert" onclick="IsEmpty();" type="submit" value="Add Question"/> 

</body>
</html>
+4  A: 

See the working example here


You are missing the required <form> element. Here is how your code should be like:

function IsEmpty(){
  if(document.forms['frm'].question.value == "")
  {
    alert("empty");
    return false;
  }
    return true;
}

HTML:

<form name="frm">
  Question: <input name="question"/> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question"/>
</form>
Sarfraz
A: 

Add an id "question" to your input element and then try this:

   if( document.getElementById('question').value === '' ){
      alert('empty');
    }

The reason your current code doesn't work is because you don't have a FORM tag in there. Also, lookup using "name" is not recommended as its deprecated.

See @Paul Dixon's answer in this post : http://stackoverflow.com/questions/608222/is-the-name-attribute-considered-outdated-for-a-anchor-tags

Rajat
A: 
if(document.getElementById("question").value == "")
{
    alert("empty")
}
Kenneth J
... there's no "id" attribute on the `<input>` element; this would only work in IE because IE is broken.
Pointy
sorry, I thought there was an ID, document.getElementsByName("question")[0].value, or just add an ID to the element
Kenneth J
A: 

Just add an ID tag to the input element... ie:

and check the value of the element in you javascript:

document.getElementById("question").value

Oh ya, get get firefox/firebug. It's the only way to do javascript.

Bal