views:

39

answers:

5

Hi Guys, I have this piece of simple code.

<html>
<head>

  <script type="text/javascript">
    function changeText()
    {
       var form = document.forms['detail'];
       form.desc.value="success";
    }
  </script>
</head>
<body>
  <form name="detail">
    <input type="text" name="desc" id="desc" >
    <input type="submit" value="changetext" onClick=changeText()>
  </form>
</body>
</html>

When i run this in Mozilla browser the value of the textbox named "desc" changes but disappears immediately...i.e it is not shown forever and becomes empty.

How can I fix it.

Regards, Vijay

+1  A: 

Try using:

<input type="submit" value="changetext" onClick="changeText(); return false;">

It looks like your page is refreshing, and that is probably why your field text disappears. If your onClick listener returns false, it will prevent this default behaviour.

Daniel Vassallo
great...this works!! Thanks :)
+1  A: 

you can give that textbox an id

and then run document.getElementById("textboxid").value ="success";

that will work in all browsers

guy schaller
A: 

The form gets submitted upon clicking the button that is typed as "submit" - the page gets reloaded.

Return false from the changeText() method and change onClick=changeText() to onClick="return changeText();" to prevent the form from getting submitted.

Alternatively, you can change the type of the button from "submit"to "button" to prevent submission. Then you'd have to add another submit button (even returning false will need you to find another way to submit the form).

Amarghosh
A: 
<input type="text" name="txt" id="txt" value="Name" onblur="if(this.value.length == 0) this.value='Name';" onclick="if(this.value == 'Name') this.value='';" />
gearsdigital
A: 

guy schaller

document.getElementById("textboxid").value ="success";

is good idea!

vijayakumar-n

try to save var form = document.forms['detail']; in a hidden input! then you will always be able to reach the form data..

blgnklc