user1543198
user1543198

Reputation: 21

change the value of input text in a form inside of form using javascript

When I click on Button, I want the input text value change to 'hello', but it doesn't seem to work, here is my code. Pros please help I'm really noob, thanks in advance!

<script type="text/javascript">
function selectfile(){
    document.uploadform.selectfile.value='hello';
}
</script>


<body>
<form name="uploadform" id="uploadform">
    <input type="text" name="selectfile" id="selectfile" value="Hi"/>
    <input name="upload_file" type="button" onClick="selectfile()" value="Button"/>
</form>
</body>

Upvotes: 2

Views: 4132

Answers (2)

Wolfram
Wolfram

Reputation: 8052

Please see this example I put up on jsfiddle:

function selectfile() {
    var form = document.forms['uploadform'];
    form.elements["selectfile"].value = 'Hello';
}

var uploadButton = document.getElementById("upload-button");
uploadButton.addEventListener("click",selectfile);

In the handler function I first get the form by its id and then set the value of the element with name selectfile (your input element). The event listener to the button is added using addEventListener.

The problem in your code is, that you called both the function and the element selectfile. So you are getting the "selectfile is not a function" error. Rename one of them and it works.

Upvotes: 2

nondefault
nondefault

Reputation: 377

That should be working. Is that the full HTML you're using? If so, you need to close your tags. It should look something like this:

<html>
<head>
    <script type="text/javascript">
    function selectfile(){
    document.uploadform.selectfile.value='hello';
    }
    </script>
</head>


<body>
    <form name="uploadform" id="uploadform">
        <input type="text" name="selectfile" id="selectfile" value="Hi"/>
        <input name="upload_file" type="button" onClick="selectfile()" value="Button"/>
    </form>
</body>
</html>

Upvotes: 1

Related Questions