views:

23

answers:

1

how to change the text of a textarea when a dropdown list is selected. Here is my code...

<html>
<head>
<script type="text/javascript">
function fifa()
{
abc=document.forms[0].browsers.value;
if(abc=="");
document.form1.text1value="you selected A";
else if
document.form1.text1.value="you selected B";
else
document.form1.text1.value="you selected C";
}
</script>
</head>

<body>

<form name="form1">
Choose which browser you prefer:
<select id="browsers" onchange="fifa()">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>

<textarea name="text1">

</textarea>
</form>

</body>
</html>

-thannx in advance

-Miss Subanki

A: 

Here is a corrected version of your function:

function fifa()
{
    var frm = document.forms[0];
    var abc = frm.browsers.value;
    if (abc === "A")
        frm.text1.value = "You selected A";
    else if (abc === "B")
        frm.text1.value = "You selected B";
    else
        frm.text1.value = "You selected C";
}

Points of interest. First, use the var keyword to declare variables inside of your functions. This ensures that your local variables will remain visible only inside the function in which they are needed. For large JavaScript programs, this is indispensible. Otherwise, without the var keyword, your variables will have global scope, possibly overwriting earlier global variables.

Second, you must learn and understand JavaScript syntax. Examine my code and yours.

Third, I am using the === operator to test for equality instead of the == operator. Both will give the same result in this piece of code, but the === operator does not enforce type coercion in JavaScript. Trust me that later down the line, this will come in useful. Study up on this issue if you are not familiar with it.

TNi
thank you, friend
subanki
dude there is 1 problem ...at 1st when u click on A..the textbox is still blank
subanki
thanx for cool points i will keep these in mind. me little week in coding but soon i will become a pro like you. :P
subanki
wat is coercion? y is ta a disvantage?
subanki
This is because you are not running `fifa()` when the page loads. Either run `fifa()` on body onload, or edit the HTML to start with the correct string in the textarea.
TNi
Type coercion occurs when you are assigning or comparing two variables of different type. There are complicated rules about how one of the variables is **coerced** into the second type. It is not always a disadvantage but often *is* a source of bugs. A Google search for "JavaScript type coercion" will provide many hits.
TNi
Thanx dude you a big pro in this stuff
subanki
if (abc === "A") frm.text1.value = "<html><head>";..if i put <html><head> , then hw can i get them in a newline ,any idea??
subanki
\n for newline ....finally found it
subanki