views:

32

answers:

2

what i wanted to do is when i clicked on a checkbox it will automatically appear on a certain part of the page. i tried to give a checkbox an onclick='displayit()'/oncchange='displayit()' where displayit() is:

function displayit(obj){
document.divnam.write(obj.value);
}

the divnam is the name of the division where i wanted the text to appear..isnt it possible?i also tried removing the divnam and putting the function itself in the division

<div name='divnam' ><script>
function displayit(obj){document.write(obj.value);}
</script></div>
A: 

Put an id on the div element instead of name so that you can easily access it. You use the innerHTML property to set the contents of the element:

function displayit(obj){
  document.getElementById('divnam').innerHTML = obj.value;
}

Putting the script inside the element would only work if you run the script while the page is loading. Declaring a function inside the element has no effect, it doesn't matter where in the page the function is declared.

Guffa
ok yay thanks very much :) i forgot about innerHTML. what about i wanted to change the content of <b></b> elements..i should use jquery right? $(b)?
kapitanluffy
what about appending another text? like for example it already show the value then when i clicked on another checkbox i wanted the value to be appended to it..like making a list or something.
kapitanluffy
@kapitanluffy: If you want to add several texts to an element, you should add them as child elements, for example `span` elements. Create an element using `document.createElement('SPAN')`, put the text in that element, and use the `appendChild` method to add it to the `div`.
Guffa
A: 

document.write only works while the page is initially loading. What you want to do now is to put some data in some part of the page, say a div with id="target":

<div id="target"></div>

And the javascript part:

<script>
function displayit(obj){
  document.getElementById('target').innerHTML=obj.value;
}
</script>
aularon