Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script to change value of a text - Javascript

Tags:

javascript

From this question i came to know text element's value can be changed by JS Set maximum number of item in Select List - html

can anyone give some code or some tips ?

My intention is not hacking, i need to know this, coz i'm writing a web app where most of the validation is done by JS

Edit
Looking for guide on running JS from client side on a page served by a server [on some text where it's readonly="true" ] !

like image 532
Sourav Avatar asked Jun 05 '11 14:06

Sourav


1 Answers

For example, if you have a html text element like this:

<p id="textelement">I am a text element</p>

You can change the text inside with JS like this:

<script type="text/javascript">
    document.getElementById("textelement").innerHTML = "New text inside the text element!";
</script>

You can use this technique with any HTML element which can contain text, such as options in a select list (<option> tag). You can select elements in other ways:

  • getElementById() Accesses the first element with the specified id
  • getElementsByName() Accesses all elements with a specified name
  • getElementsByTagName() Accesses all elements with a specified tagname

More info here.

PS - If you want to change the value of an element's attribute, and not its inner text, you should use the setAttribute() method; for example, if you have:

...
<option id="optionone" value="red">Nice color</option>
...

and want to change the value attribute, you should do:

<script type="text/javascript">
    document.getElementById("optionone").setAttribute("value", "green");
</script>

More about this here.

like image 195
faken Avatar answered Nov 18 '22 18:11

faken