最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change form element values in HTML - Stack Overflow

programmeradmin2浏览0评论

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 bees empty.

How can I fix it.

Regards, Vijay

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 bees empty.

How can I fix it.

Regards, Vijay

Share Improve this question edited Jul 19, 2010 at 7:42 Matt Mitchell 41.9k35 gold badges121 silver badges185 bronze badges asked Jul 19, 2010 at 7:41 user376539user376539 552 gold badges2 silver badges5 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

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.

you can give that textbox an id

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

that will work in all browsers

<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='';" />

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..

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).

发布评论

评论列表(0)

  1. 暂无评论