473,395 Members | 1,462 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

RE: Javascript GetElementByID

Hi Folks,

I have designed a HTML page, where i have a dop down box with 5 names. When a particular name is selected from a drop down, an approproiate email address should be automaticallay set to a text box which holds email adresses.

Here is the code below : Please help
Expand|Select|Wrap|Line Numbers
  1. <td>
  2. <select name="Cat" id="Cat" style="width: 238px">
  3.        <option value="Select">Select</option>
  4.        <option value="Mark">Mark</option>
  5.        <option value="Jay">Jay</option>
  6.        <option value="Chris">Chris</option>
  7.        <option value="Martin">Martin</option>
  8.  </select></td>
  9. <td><input type="text" name="Cat_Email" style="width: 250px" /></td>

I am looking for a Javascript code, so that if "Mark" is selected from the drop down box, the text box "Cat_Email" should automatically get set with his email address "XXX".. If Jay is selected then YYY etc.

Please Help..

Thanks in advance.

Regards,
Chandhseke
Dec 1 '09 #1

✓ answered by Dormilich

How can we set the value attribute to a text box while a user selects the ITEM CHANDRA.?
that is quite simple. when you select Chandra, you change the value of the select element (but the value of the option element stays the same)
Expand|Select|Wrap|Line Numbers
  1. // this function is applied to the select element
  2. // and because the scope changes this refers to the element itself
  3. function addEmail()
  4. {
  5.     // += appends some text to something
  6.     document.getElementById("textbox").value += this.value;
  7. }
  8. // call the function above on the select element in case of an onchange event
  9. // IE has its own way (google for addEvent() (crossbrowser event handling))
  10. document.getElementById("select").addEventListener("change", addEmail, false);
to pass "Chandra" to a field (e.g. hidden input) simply add
Expand|Select|Wrap|Line Numbers
  1. // the input field
  2. // get the text node from the currently selected option element
  3. document.getElementById("hidinp").value = this.options[this.selectedIndex].text;

49 3856
Dormilich
8,658 Expert Mod 8TB
what about putting the email address in the option’s value attribute? the you can copy over.
Expand|Select|Wrap|Line Numbers
  1. // in case of event (select element)
  2. function populate()
  3. {
  4. // put an id to the input element
  5.     document.getElementById("catmail").value = this.value;
  6. }
Dec 1 '09 #2
I am trying the following, please advise if this is a wrong approach.
Expand|Select|Wrap|Line Numbers
  1. <script language="Javascript">
  2. function Cat_Dir()
  3. {
  4. var res;
  5. var w=document.SDS_step_one.Cat.selectedIndex;
  6. var selected_text=document.SDS_step_one.Cat.options[w].value;
  7. if (selected_text == "Mark")
  8. {
  9. document.SDS_step_one.CatEmail.value = "ABC"
  10. }
  11. </script>
But this is not working to me..Please correct the code for me!!
Dec 1 '09 #3
I did it, i got the answer.

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript"> 
  2. function addit(){ 
  3.     if(document.getElementById("cat").value=="Mark") 
  4.     { 
  5.         document.getElementById("catEmail").value="XXX" 
  6.     } 
  7.     if(document.getElementById("cat").value=="Jill") 
  8.     { 
  9.         document.getElementById("catEmail").value="AABC" 
  10.     } 
  11.     if(document.getElementById("cat").value=="Rock") 
  12.     { 
  13.         document.getElementById("catEmail").value="Apache" 
  14.     } 
  15. </script>
Dec 1 '09 #4
Thanks for your support!!
Dec 1 '09 #5
Dormilich
8,658 Expert Mod 8TB
just a question, do you need this dropdown for anything else than this email thingy?
Dec 1 '09 #6
No i just wanted to automatically display the associated email address of the person when a name is selected from a drop down... This drop down contains only 5 - 6 names so i thought of hard coding it using Javascript.. Is there any other way since i have similar requirement where the drop down contains too many Names.

Please advise if any other approach that i can follow. Thank you!!
Dec 2 '09 #7
Dormilich
8,658 Expert Mod 8TB
then I’d say, put the email addresses in the value attrribute of the option element and pass over the value to the input field (or whatever element).
like
Expand|Select|Wrap|Line Numbers
  1. <select … >
  2.     <option value="mark@example.org">Mark</option>
  3.     <option value="jane@example.org">Jane</option>
  4.     …
  5. </select>
Dec 2 '09 #8
But i want to see both "Name" and "Email" address stored separately in the database.. And more over, there is an automated email mechanism incorporated which will take this email address as a recipient.

Basically, we have a drop down and a text box.. If a name, say "Chandh" is selected from the drop down, his email address should get set to text box.
Dec 3 '09 #9
Dormilich
8,658 Expert Mod 8TB
But i want to see both "Name" and "Email" address stored separately in the database..
no problem. send the email to one input the name to another input and don’t name the select (so the value doesn’t get submitted).

If a name, say "Chandh" is selected from the drop down, his email address should get set to text box.
I already got that point. this is what my initial code would do (ok, you need to use += instead of =)
Dec 3 '09 #10
1. Yes. Since i am very new and still a learner I understand the above statement but it would be great if you give me a sample code.

2. Regarding binding of drop down values, how can we pass a selected drop down items value attribute to a text box using javascript function.

Example:
<option value="chandra@example.org">CHANDRA</option>

How can we set the value attribute to a text box while a user selects the ITEM CHANDRA.?

Thanks is advance.

Chandhseke
Dec 6 '09 #11
Dormilich
8,658 Expert Mod 8TB
How can we set the value attribute to a text box while a user selects the ITEM CHANDRA.?
that is quite simple. when you select Chandra, you change the value of the select element (but the value of the option element stays the same)
Expand|Select|Wrap|Line Numbers
  1. // this function is applied to the select element
  2. // and because the scope changes this refers to the element itself
  3. function addEmail()
  4. {
  5.     // += appends some text to something
  6.     document.getElementById("textbox").value += this.value;
  7. }
  8. // call the function above on the select element in case of an onchange event
  9. // IE has its own way (google for addEvent() (crossbrowser event handling))
  10. document.getElementById("select").addEventListener("change", addEmail, false);
to pass "Chandra" to a field (e.g. hidden input) simply add
Expand|Select|Wrap|Line Numbers
  1. // the input field
  2. // get the text node from the currently selected option element
  3. document.getElementById("hidinp").value = this.options[this.selectedIndex].text;
Dec 6 '09 #12
DMsy2
15
Consider;


Expand|Select|Wrap|Line Numbers
  1. <select on{event}="GetValues(this);" >
  2. <option value="mark|Mark Jones|mark@example.org">Mark</option>
  3. <option value="jane|Jane Smith|jane@example.org">Jane</option>
  4. </select>
  5.  
  6.  
  7. <script type="text/javascript">
  8. // <![CDATA[
  9.  
  10. function GetValues(el)
  11. {
  12.     data = el.options[ el.selectedIndex ].value;
  13.     info = data.split("|");
  14.  
  15.     document.getElementById("catuser").value = info[0];
  16.     document.getElementById("catname").value = info[1];
  17.     document.getElementById("catmail").value = info[2];
  18. }
  19.  
  20. // ]]>
  21. </script>
Dec 6 '09 #13
Dormilich
8,658 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. // <![CDATA[
  2. // ]]>
you only need this if you serve your document with the "text/xml" or "application/xhtml+xml" MIME type (which hardly anyone does)

Expand|Select|Wrap|Line Numbers
  1. function GetValues(el)
  2. {
  3.     data = el.options[ el.selectedIndex ].value;
  4.     // …
  5. }
that’s the same as
Expand|Select|Wrap|Line Numbers
  1. data = this.value;
(the currently selected option’s value is the value of the <select> element)

Expand|Select|Wrap|Line Numbers
  1.     info = data.split("|");
  2.  
  3.     document.getElementById("catuser").value = info[0];
  4.     document.getElementById("catname").value = info[1];
  5.     document.getElementById("catmail").value = info[2];
  6. }
good idea
Expand|Select|Wrap|Line Numbers
  1. <select on{event}="GetValues(this);" >
  2. </select>
once you overcome IE’s poor event handling, inline JavaScript appears chunky
Dec 6 '09 #14
DMsy2
15
1/ CDATA
It is good practice to do ths and allows for validation tools to run properly. So I use it.

2/ not just "el.value"
This is an example, so I've written it to show what is happening and how/why, in case of future extension.
Dec 6 '09 #15
Dormilich
8,658 Expert Mod 8TB
2/ not just "el.value"
This is an example, so I've written it to show what is happening and how/why, in case of future extension.
as if select.value wouldn’t describe what’s happening…
Dec 6 '09 #16
DMsy2
15
It would in the restricted case of a single select.
If however you were traversing a multiple selection list, or some other scenario, then knowing the full derivation would help.

I'm sorry, you seem to be giving me a hard time for just trying to help people?
Dec 6 '09 #17
Dormilich
8,658 Expert Mod 8TB
I'm sorry, you seem to be giving me a hard time for just trying to help people?
I am just trying to figure out, what in this case would be the most efficient approach. and of course what the most efficient approach is, can (and probably will) always be debated. and eventually, debates can bring you further in understanding, how JavaScript works.
Dec 6 '09 #18
acoder
16,027 Expert Mod 8TB
Don't worry, DMsy2, Dormilich means well :)

On the CDATA, personally, I'd say that you never need it. Why? Put your JavaScript in separate files. Problem solved.

PS. welcome to Bytes and thanks for your input!
Dec 7 '09 #19
When i used the above code in onchange event, the textbox will get set with a value "Undefined". Please help?
Dec 7 '09 #20
Expand|Select|Wrap|Line Numbers
  1. function addEmail() 
  2.     // += appends some text to something 
  3.     document.getElementById("textbox").value += this.value; 
I called this function within <Select>, but the text box is set with a value "Undefined". Since we are using +=, if we select an item thrice from dropdown, then 3 times a word "undefined" gets set to the textbox "Cat_Email".

Please advise something?
Dec 7 '09 #21
Dormilich
8,658 Expert Mod 8TB
how did you attach this function to the event?
Dec 7 '09 #22
With the help of an on change event. I enclosed the function within <script> tags as we normally do (within <head> section) and called the function with the help of an onchange event.
Dec 7 '09 #23
Dormilich
8,658 Expert Mod 8TB
and called the function with the help of an onchange event.
may I see the code for this?
Dec 7 '09 #24
Now it's working, i made a few changes to the code that you provided.

function addEmail()
{
document.getElementById("TextBox").value += this.value;
}
I replaced += this.value with the below:
document.getElementById("TextBox").value = document.getElementById("Select").value
It is working now. Thanks for your support.
Dec 7 '09 #25
Dormilich
8,658 Expert Mod 8TB
ahh, yes. good ole event handling. once you understand it, it’s nearly as cool as sliced bread.
Dec 7 '09 #26
Yes, you are exactly correct. Thanks again for all your support. Your knowledge about Javascript is really outstanding.

Bye :)
Dec 7 '09 #27
Dormilich
8,658 Expert Mod 8TB
you’ll get there, too. though not this time. (pun intended)

Your knowledge about Javascript is really outstanding.
I don’t think so, I just happen to do some proper background reading.
Dec 7 '09 #28
May i know why is that used for? I am a newbie, have no much deeper idea about JS.
Dec 7 '09 #29
Dormilich
8,658 Expert Mod 8TB
you mean the "this"?
________________
Dec 7 '09 #30
Yes I need to know the difference
Dec 7 '09 #31
Dormilich
8,658 Expert Mod 8TB
the difference between "this" and …?
Dec 7 '09 #32
Sorry for the confusion. I want to know the difference between "this" and the code i replaced with "this.value". Technically, i understood but i need to know why "this.value" gave an error (infact displaying a word "undefined" on all selections.

Why actually "this" is used for?

Again sorry for bothering you a lot in this!!
Dec 7 '09 #33
Dormilich
8,658 Expert Mod 8TB
i need to know why "this.value" gave an error
short answer: because you call the function in the wrong scope.

longer answer:
first you have to understand, that JavaScript (as a programming language) is all about objects. (there are some primitive data types though)

that means, that even your HTML page to JavaScript is just an enormous bunch of objects. (more to that later)

but these objects are not equal, they have a "hierarchy". this hierarchy is called scope. you can imagine that a particular scope is like a layer or an environment of an object. you may have heard that the environment inside a function is called local scope, and everything that is defined top level (e.g. not inside a function) is called global scope. meaning if you have a variable defined inside a function, it can access (read) every other variable, that has the same or a higher scope.
(you probably have to google for articles regarding this stuff to get a deeper understanding)
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. var x = 0; // global scope
  3. var y = "some text in global scope";
  4.  
  5. function myFunc1()
  6. {
  7.     var y = 1; // local scope
  8.     var a = "another local var";
  9.     alert(y); // shows the local variable ("1") and not the global one
  10.     alert(x); // shows "0"
  11. // show local variable x, if there ain’t any, look in the next level (global scope)
  12. }
  13.  
  14. function myFunc2()
  15. {
  16.     var z = "Byte"; // local
  17.     alert(z); // show local
  18.     alert(a); // shows "undefined"
  19. // because a is neither defined in local scope, nor in global scope.
  20. // it only exists in the local scope of myFunc1
  21. }
  22. </script>
you might have guessed … functions are objects (weird, but true)

you might get the dim idea, that when your change event appended "undefined" exactly this is happening, but why? because there are some functions, that change the scope of a function (or object).

those functions are (not a complete list)
  • setTimeout()
  • setInterval()
  • addEventListener()
  • removeEventListener()
  • call()
  • apply()
and I forgot to mention somthing important, even the global scope is tied to an object. the window object (the same as in window.open()).

if you read about objects, you learn some basic features they have, that is, they have members called properties and methods*. properties are "variables", that can only be called from the object, that owns these properties.

* - methods are a synonym for functions, an object may execute. but from the JavaScript-point-of-view that doesn’t matter, because everything is an object, be it an array, a string, a number (…) or a function

so let me rephrase the above list
  • window.setTimeout()
  • window.setInterval()
  • Element.addEventListener()
  • Element.removeEventListener()
  • Function.call()
  • Function.apply()
I said, these fu–methods change the scope of the functions they execute. that is, the keyword this no longer points to the scope, the function was defined in but the scope of the executing object.

example:
Expand|Select|Wrap|Line Numbers
  1. // HTML
  2. <div id="test" title="some meaningless text">just an example</div>
  3.  
  4. // JS
  5. // define a function showing the title property of the current object at execution time
  6. function myFunc()
  7. // the same as: window.myFunc = function()
  8. // though there are some utterly fine differences
  9. {
  10.     alert(this.title);
  11. }
  12. // get the element object
  13. var div = document.getElementById("test");
  14. // would be the same as
  15. window.div = document.getElementById("test");
  16.  
  17. // alerts "undefined", because there is no window.title property (… yet ;) )
  18. myFunc();
  19. // window.myFunc();
  20.  
  21. // alerts "some meaningless text" when you click on the div
  22. div.addEventListener("click", myFunc, false);
you may argue, that you have defined the event, but it still doesn’t work…

… well, inline JavaScript is different (and IMO ugly)

if you code
Expand|Select|Wrap|Line Numbers
  1. <div id="test" title="some meaningless text" onclick="myFunc()">just an example</div>
then myFunc() is still executed in global scope (aka window) showing "undefined".

however, you can explicitly pass a reference to the current object (even more ugly :).
Expand|Select|Wrap|Line Numbers
  1. <div onclick="someFunc(this)">kick me</div>
(I don’t wanna go into detail here)

another way to bind the event would use the onevent attribute, but this does not allow for event capturing** (which is possible with addEventListener)

** - note: IE does not support event capturing at all
Dec 7 '09 #34
Thats really a very good piece of information. Thanks a lot folk.

Regardong the main subject of this thread. How can set the drop down ITEM selected (Not the value) to a hidden text box and where should i call this function?

Chandhseke
Dec 8 '09 #35
Dormilich
8,658 Expert Mod 8TB
dropdown item = selected option element text content?

just the same event as if you were using the value. you only have to access the piece of information differently than in case of value (you need the select.options list)
Dec 8 '09 #36
Hi Folk,

Can you give me an example please? I did it few times but did not work to me, am running short of time for my project submission.

I repeat the question: I want the drop down selected item to pass to a hidden text box using JavaScript.

<option value="Chandhseke@bytes.com">Chandhu</option>
I want to pass "Chandhu" to a hidden text box so that i can insert this value intoo database.

Thanks in advance. This subject discussion taught me a lot about javascript.
Thanks again.

Chandhseke
Dec 9 '09 #37
Dormilich
8,658 Expert Mod 8TB
I already did. post #12, 2nd code box.
Dec 9 '09 #38
That is not working to me ( I maay not using it correctly either). I tried the one in post #12 anad below: Both did not gave me a solution
functiion addemail()
{
document.getElementByID("hidtext").value = document.getElementById("Select").options[i].text;
}
Please advise.

Chandhseke
Dec 10 '09 #39
Dormilich
8,658 Expert Mod 8TB
point 1: "function" contains only a single "i"
point 2: "getElementByID()" is an incorrect call (it’s getElementById(), JavaScript is case-sensitive)
point 3: the variable "i" is undefined
point 4: the example code shows, how to use the options property correctly
Dec 10 '09 #40
document.getElementById("text").value = this.options[this.selectedIndex].text;
In the above example of post #12, can we write a code without using "this" property since the above code returned a JS error while i run the script.
Dec 10 '09 #41
Dormilich
8,658 Expert Mod 8TB
sure, replace this by a reference to the select element. though if you’re already using the function, that passes the email address (through this) it would make sense to add that line into the function (unless you can’t do this due to some reasons)

since the above code returned a JS error while i run the script.
most probably called in the wrong scope.

PS. if you keep all your JavaScript in an external file, your HTML will look much more lucid (plus you don’t have to update the HTML if something changes in the JS).
Dec 10 '09 #42
Do you mean to say like below,
document.getElementById("hidtext").value = document.getElementByID("select").options[this.selectedIndex].text;
Correct the above code if i am wrong, i am trying to understand how exactly does it works.

Chandhseke
Dec 10 '09 #43
Dormilich
8,658 Expert Mod 8TB
1) JavaScript is case-sensitive
2) I still can see a "this"
Dec 10 '09 #44
I think its better you please correct the example code that i sent you!!.
Dec 10 '09 #45
Dormilich
8,658 Expert Mod 8TB
and next time, when I’m not around to have a look at? you need to learn to get better and that requires effort.
Dec 10 '09 #46
Yes thats right!! I was running out of time so was in a hurry to get an answer.

So we need to replace "this" with a select item reference.

document.getElementById("hidtext").value = document.getElementById("select").options[select.selectedIndex].text;

or

document.getElementById("hidtext").value = document.getElementById("select").options[document.getElementById("select").selectedIndex].text;
Please advise.
Dec 10 '09 #47
Dormilich
8,658 Expert Mod 8TB
second one looks correct. first one: select is undefined.

PS. as you can see, there is less code to write using this (one argument to use it)
Dec 10 '09 #48
Thats awesome you made me think and do it by my own. I really very thank ful to you. i always look forward to work with you in future.

Thanks a lot and the code is working as intended!!

Chandhseke
Dec 10 '09 #49
Dormilich
8,658 Expert Mod 8TB
I still know how hard it was to understand Closures.
Dec 10 '09 #50

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.