Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using function to set variable?

Status
Not open for further replies.

djtizzlemaster

Programmer
Mar 5, 2008
17
US
I am creating an order form. There is a drop-down list for Referral (<select name="referral">). The options are like Internet, Magazine, etc. The option of particular interest here is Other. If (and only if) the user select Other from the drop-down list, I want a text field to appear. Here's how I'm trying to go about doing it:



~~~The event:

<option onclick="otherz()">(Other)</option>



~~~The function:

<head>
<script type="text/javascript">
<!--
function otherz() {
var other_var = "true"
}
//-->
</script>
</head>



~~~The if statement in the body:

<script type="text/javascript">
<!--

if(other_var == "true"){
document.write("<td>Other:</td><td><input type='text' size='20' maxlength='40' name='other_referral'></td>");
} else {
document.write("<td>&nbsp;</td><td>&nbsp;</td>");
}

//-->
</script>



~~~

Where am I going wrong?
 
Can you post a URL to the page so that we can see all the code?

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
First off, I'll explain why I asked for the link - most professionals don't use document.write, so I figured you were going to post a link to a site hosted on an edu domain because document.write usually stinks of a homework assignment posted by a student. And order forms are a common assignment. You passed the test [lol]

All that aside, you're not using document.write correctly. If used dynamically, it will completely overwrite the contents of the page - for this reason it should be used [!]ONLY[/!] as the page is loading (really it shouldn't even be used then - there are other preferred methods, see my above comment about students). You should either use DOM methods or the easier (and personally preferred method) of modifying the innerHTML of an element - use google to figure out how this works since there's plenty of documentation on it.

Also, AFAIK the onclick handler is not supported by <option> tags. Instead you should put an onchange handler on the parent <select> tag and check to see if the appropriate <option> was selected - then kick off your function that way.

I'll also offer a few friendly words of advice, so please take them as such and do not get offended. Since you offer web design through your webpage it would be beneficial for you to learn the trade. All your pages are done in quirks mode (no doctype defined), there is rampant use of deprecated tags like font (you should seriously consider learning CSS if you want to "make it" in the web design world), and the table based layouts like the one used on your order form page are sooooooooooo 90's. Like I said, please take this as constructive criticism instead of insults, because if you are serious about web design then these are things you need to know.

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Thank you for the criticism!

Now, I'm thinking it's going to go like this:

<select name="referral" onchange="otherz()">

But I realize that this is going to execute the otherz() function regardless of which option is selected, which is why you said "check to see if the appropriate <option> was selected."

I'm just not sure how I would check that. Would it be like this?

onchange="if(referral == "(Other)"){otherz()}"

I'm just not sure about the referral part.. is the syntax correct here?
 
1-> To retrieve the selected option in a select tag, just put an id attribute on it (let's say "myChoice") and test the select DOMobject value.
2-> Another point : defining your "other_var" variable inside a function reduces its scope to the only function. As variables declarations are not mandatory in javascript, when, later in your page, you try to test the value of this variable, you don't test the variable initialized in your function but a new undeclared one.
3->javascript knows how to handle booleans and have the "true" and "false" keywords reserved for that. As is, you'd better use them instead of string values.

Once these things corrected, your code should look like this :
Code:
<select id="myChoice" onclick="otherz();">
 ...
 <option>(Other)</option>
</select>

<script type="text/javascript">
<!--
var other_var = false;

function otherz() {
  if (document.getElementById("myChoice").value=="(Other)") {
    other_var = true;
  }
}
//-->
// tests :
if (other_var) {
// creating TDs with input.
} else {
// creating empty TDs.
}
</script>

4-> I agrees with kaht about the document.write and CSS.
The way you create your TDs might work on page load but won't dynamically change the content of your TDs on every change on the select.
To do it, just put an id to the TDs you want to change the content. Then, you can use innerHTML (or createElement) to fill them like this :

Code:
<select id="myChoice" onclick="otherz();">
 ...
 <option>(Other)</option>
</select>
...
..
<TABLE><TBODY><TR>
  <TD id="otherLabel">&nbsp;</TD>
  <TD id="otherField">&nbsp;</TD>
</TR></TBODY></TABLE>
...
..
<script type="text/javascript">
<!--

function otherz() {
  var labelTD = document.getElementById("otherLabel");
  var fieldTD = document.getElementById("otherField");

  if (document.getElementById("myChoice").value=="(Other)") {
    labelTD.innerHTML="Other:";
    fieldTD.innerHTML="<input type='text' size='20' maxlength='40' name='other_referral'>";
  } else {
    labelTD.innerHTML="&nbsp;";
    fieldTD.innerHTML="&nbsp;";
  }
}
//-->
</script>

As is, the TD content will change each time you change the select value !!!

Water is not bad as long as it remains outside human body ;-)
 
Targol's suggestions should definitely get you started on the right track. The only thing I would change is this:
Code:
<select id="myChoice" onclick="otherz([!]this[/!]);">
 ...
 <option>(Other)</option>
</select>

<script type="text/javascript">
<!--
var other_var = false;

function otherz([!]obj[/!]) {
  if ([!]obj[/!].value=="(Other)") {
    other_var = true;
  }
}
//-->
// tests :
if (other_var) {
// creating TDs with input.
} else {
// creating empty TDs.
}
</script>

The getElementById method is not very fast - this is especially noticable when you run it inside of a loop. So, when optimizing my javascript code one of the things I will look for is how many getElementById methods can I get rid of. In this instance, the otherz function is getting triggered by the <select> tag, so that tag can pass a reference to itself as a parameter in the function call. This alleviates the need to "find" itself once inside the function using getElementById.

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
You're right kaht, your solution is much better than mine. thanks for this correction.


Water is not bad as long as it remains outside human body ;-)
 
I was able to get Targol's solution to work, but not kaht's. You guys say that kaht's version is better, however, so I would prefer to be able to get that one working. Below is how I'm trying to get it to work. I assume it is an overly simple error on my part. Am I supposed to replace "this" or "obj" with some specific value, like obj.referral or select.referral or something? As you can see, I am a complete beginner when it comes to JavaScript...

Code:
<head>
<script type="text/javascript">
<!--
var other_var = false;

function otherz(obj) {
  if (obj.value=="(Other)") {
    other_var = true;
  }
}
//-->
</script>
</head>

      <table width="311" border="0" cellspacing="0" cellpadding="3">
        <tr>
          <td width="111">Referral:</td>
          <td width="188">
          		<select name="referral" id="myChoice" onclick="otherz(this);">
				<option>Internet</option>
                <option>Magazine</option>
                <option>Phone Book</option>
                <option>Repeat Customer</option>
                <option>Word of Mouth</option>
                <option>(Other)</option>
                </select>
          </td>
        </tr>    
        <tr>
        <script type="text/javascript">
	        if (other_var) {
	          <td>Other:</td>
	          <td><input type='text' size='20' maxlength='300' name='other_referral'></td>
			} else {
	          <td>&nbsp;</td>
	          <td>&nbsp;</td>
			}
		</script>
		</tr>
      </table>
 
Like I put in my first informative post, you should use the onchange handler on the <select> box - not the onclick handler. Also, you haven't assigned [!]values[/!] to any of your options, so instead you will have to check against the [!]text[/!] of the option. On a side note, the value check will work if you assign values to the option tags (denoted in orange below)
Code:
<head>
<script type="text/javascript">
<!--
var other_var = false;

function otherz(obj) {
  if (obj.[!]options[obj.selectedIndex].text[/!]=="(Other)") {
    other_var = true;
  }
}
//-->
</script>
</head>

      <table width="311" border="0" cellspacing="0" cellpadding="3">
        <tr>
          <td width="111">Referral:</td>
          <td width="188">
                  <select name="referral" id="myChoice" [!]onchange[/!]="otherz(this);">
                <option>Internet</option>
                <option>Magazine</option>
                <option>Phone Book</option>
                <option>Repeat Customer</option>
                <option>Word of Mouth</option>
                <option [COLOR=orange black]value="(Other)"[/color]>(Other)</option>
                </select>
          </td>
        </tr>    
        <tr>
        <script type="text/javascript">
            if (other_var) {
              <td>Other:</td>
              <td><input type='text' size='20' maxlength='300' name='other_referral'></td>
            } else {
              <td>&nbsp;</td>
              <td>&nbsp;</td>
            }
        </script>
        </tr>
      </table>

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top