0

I've searched online and this website alike for a simple and adaptable solution but alas, no joy.

The desired process:

  1. The user selects an <option> from a <select> list. e.g. a name.
  2. The value of a read-only text box automatically populates based on the selected <option>. e.g. a phone number corresponding to the name.
  3. Finally, both the <select> box and text box must each have their own values. i.e. a name and a phone number respectively.

The basic mark up:

When this changes, update the value of my text box:

<select id="name" name="name">
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>

Value contingent on the value of above box:

<input type="text" id="phonenumber" name="phonenumber" value="">

My question:

How do I achieve this using jQuery or regular Javascript? Please answer this from the perspective of a client side novice.

The solution (thanks to corroded):

I added the following to the head of my document:

 <script type="text/javascript" src="jquery.js"></script>          
 <script type="text/javascript">  
 $(document).ready(function() {                                       
    $("#name").live("change", function() {
      $("#phonenumber").val($(this).find("option:selected").attr("data-phonenumber"));
    })
 });                                     
 </script>

...and the following to the body of my document:

<select id="name" name="name">
<option value="" selected="selected">Please select...</option>
<option value="Elvis" data-phonenumber="11111">Elvis</option>
<option value="Frank" data-phonenumber="22222">Frank</option>
<option value="Jim" data-phonenumber="33333">Jim</option>
</select>

<input type="text" id="phonenumber" name="phonenumber" value="" readonly="readonly">

For more information on the use of data-somename as an attribute, as suggested by corroded, refer to the following links:

http://ejohn.org/blog/html-5-data-attributes/

http://blogs.sitepoint.com/rel-not-a-custom-attribute/

Dominor Novus
  • 137
  • 2
  • 10

4 Answers4

2

add a "data-phone-number" value on your options:

<option value="Elvis" data-phone-number="77777">Elvis</option>

in your jquery:

$("#name").live("change", function() {
  $("#phonnumber").val($(this).find("option:selected").attr("data-phone-number"));
})

refactor as needed :)

corroded
  • 21,406
  • 19
  • 83
  • 132
  • @Dominor - if like this answer, why don't you check it and mark it as correct? – eykanal May 06 '11 at 03:55
  • That worked out great, much thanks corroded! I didn't realize that I could create an attribute and call on it in that manner. Thank you for paying attention to my third stipulation regarding my requirement for select box and text box having separate values. I've added the full coded solution to my question for clarity and record. – Dominor Novus May 06 '11 at 04:00
  • @eykanal: I was in the process of it. With decorum in mind, I was responding by way of comment to the other members who provided an answer to my question. Don't worry, exiting without closing the door behind you on support based community forums is a pet hate of mine too. ;-) – Dominor Novus May 06 '11 at 04:06
  • @Dominor - not a problem, and thanks. I saw your lower rep and thought you may be a newcomer, so I figured I'd give a friendly nudge. – eykanal May 06 '11 at 04:08
  • just a note, it is generally accepted to use the "data-" prefix for anything regarding additional data in your attribute tags as anything else will probably give off some warning or whatnot(not sure..but it's best to use the data- tag) reference here: http://ejohn.org/blog/html-5-data-attributes/ – corroded May 06 '11 at 04:13
  • @corroded: Thanks again. I've updated the code by prefixing the attributes with `data-` as suggested. Cheers for the link and explanatory information. – Dominor Novus May 06 '11 at 04:24
  • no problem. as i am fond of refactoring my own code, you could also read up on http://stackoverflow.com/questions/4204316/jquery-live-vs-delegate just to optimize it more, but yeah it's not needed that much in your case as you only have 1 live call. just a heads up :) – corroded May 06 '11 at 04:26
  • @eykanal: Nudges are welcomed and yes, I'm a newbie to Stack Overflow. :-) – Dominor Novus May 06 '11 at 04:43
  • @corroded: Cheers, I've bookmarked the thread should I encounter a scenario where I need to differentiate between live() and delegate(). Though it's mostly abstract to me, judging by your comment, it's related to the amount of calls in the head of my document. I'm not sure what you mean by "refactoring". Also, I came across the following article supporting your advocacy of using the "data-" prefix: http://blogs.sitepoint.com/rel-not-a-custom-attribute/ – Dominor Novus May 06 '11 at 04:50
  • refactoring = making your code cleaner, and more manageable http://en.wikipedia.org/wiki/Code_refactoring. I'm just saying that as you declare more live() calls, your document may tend to slow down and it's better to use delegate in that case. but that's just in the long run :) – corroded May 06 '11 at 05:12
0

I would do something like:

<select id="name" name="name">
  <option value="0123456789">Elvis</option>
  [...]
</select>

and then

$('#name').change(function(){
  var thisphone = $(this).val();
  $('#phonenumber').val(thisphone);
});

or

$('#name').change(function(){
  $('#phonenumber').val($(this).val());
});

depending on how you want to work with your variables

dan
  • 856
  • 9
  • 20
  • Thank for the answer postiv but corroded's earlier solution done the trick. Does your solution allow for the select box and text box to be able to post different values (see my third stipulation under "The desired process:")? – Dominor Novus May 06 '11 at 03:58
  • No it wont. But corroded's answer is a great one. but it is not W3C valid, but it does the job! – dan May 06 '11 at 19:23
0

You can try this.

$('#name').change(function(){
    $('#phonenumber').val($(this).val());
});

If you would like it to display the phone number just set up your HTML to have the value of each option be the phone number. For instance.

<option value="5555555555">Frank</option>
mhiggins
  • 56
  • 3
  • Hey mhiggins, thanks for the answer but as mentioned to postiv, corroded's earlier solution done the trick. I'll address the same question you: does your solution allow for the select box and text box to be able to post different values (see my third stipulation under "The desired process:")? – Dominor Novus May 06 '11 at 03:58
  • Dominor, You're right. His will work. The data attribute will work just fine as described above. You could also put a different value in the rel tag and call that replacing this line `$('#phonenumber').val($(this).attr('rel'));` – mhiggins May 06 '11 at 04:19
  • After a little cursory research on your suggestion I came across the an article insisting that REL should never be used as custom attribute and furthermore, it should only be used on a and link tags (http://blogs.sitepoint.com/rel-not-a-custom-attribute/). Should I take this a pinch of salt? Apologies if I'm coming across as being obtuse - I appreciate your time. – Dominor Novus May 06 '11 at 04:42
  • @dominor : Not obtuse at all. Research is never a bad thing. That article has very valid points. At the end the author leaves it open to "do what fits best in your situation". There really isn't a clear cut answer for it. If you need to pass data and there isn't a vehicle for doing that you improvise. In the many applications I've built I have used the rel tag with no troubles. If you can ensure everyone using your code will be on an HTML5 compatible browser then you'll want to go with the data- attribute. – mhiggins May 06 '11 at 16:20
0

You can also do this without tying the select box and the phone numbers so tightly together. Use JSON notation to set up objects that hold all of your person's info, such as:

<script type="text/javascript">
    var people = {
        Elvis:  {
            phone: "555-5555"
            },
        Frank: {
            phone: "123-4567"
            },
        Jim: {
            phone: "987-6543"
            }
        };

    window.onload = function() {
        var list = document.getElementById("name");
        list.onchange = function() {
            document.getElementById("phone").value = people[this.value].phone;
        }   
    }
</script>

Basically, we're just creating three objects, "Elvis", "Frank" and "Jim" inside a bigger object called "people". Each object has a phone property that you can access with the dot notation, as I've done (i.e. people["Elvis"].phone), or the array notation (i.e. people.Elvis["phone"]]).

To make things easy, I am using the "this" keyword since when called from within the "onchange" event handler, it refers to the object that fired the event -- the select box. So "this.value" refers to the value on the select box.

Now your select stays pretty simple:

<select id="name" name="name">
    <option value="Elvis">Elvis</option>
    <option value="Frank">Frank</option>
    <option value="Jim">Jim</option>
</select>

<br />
<input type="text" id="phone" />
Nick Ramirez
  • 473
  • 5
  • 15
  • Thanks for the alternative approach and overview. I've successfully tested it. It's interesting how you used the .notation by structuring the value of phone for each of the names. It's provided me with an insight into the architecture of JavaScript. As you've implied, it certainly streamlines the select box mark-up. I'll keep this bookmarked to dissect at a later stage should I require it though I'll run with corroded's approach mainly because I have in interest in familiarizing myself with jQuery. – Dominor Novus May 06 '11 at 05:09