Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an input text from javascript?

I have this simple code that speaks for itself.Here it is:

<script language='javascript"> 
    function check() {} 
</script> 
<div id="a">input type="text" name="b"> 
<input type="button" onClick=" check(); ">

All i want is that when i press the button, the text field gets a value updated to it.

I tried using b.value=" C " but it doesnt seem to work.

like image 646
anand Avatar asked Mar 05 '10 17:03

anand


2 Answers

<script language="javascript"> 
     function check() {
          document.getElementById('txtField').value='new value here'
     } 
</script>

<input id="txtField" type="text" name="b"> <input type="button" onClick=" check(); ">

This will do. I gave it an ID, and used getElementById('txtField') using the id, and updated it's value.

like image 94
Marcos Placona Avatar answered Sep 29 '22 12:09

Marcos Placona


You seem to be thinking that giving a form input a name attribute makes it addressable as though it were a global variable. It doesn't. There is a syntax for that, and you would have to use something like:

document.forms[0].b.value = "C";

in order to get to address it successfully. You are putting your form elements inside a form, aren't you?

Do it that way, or use an ID along with the getElementById method, as mplacona suggests.

like image 36
Robusto Avatar answered Sep 29 '22 14:09

Robusto