1

I have been researching how to copy a a text field value into a drop down menu and have only been seeing how to accomplish the opposite. Can somebody help me tweak this code so it will copy the shipping city value (text field) into the billing city (drop down)?

    <html>
    <head>
    <title>Untitled Document</title>
    </head>

    <body>
    <P>
    <script type="text/javascript">
    <!--
    function FillBilling(f) {
      if(f.billingtoo.checked == true) {
      f.billingname.value = f.shippingname.value;
      f.billingcity.value = f.shippingcity.value;
      }
    }
    // -->
    </script>
    <TABLE BORDER=1><TR><TD BGCOLOR="eeeeee">
    <b>Mailing Address</b>
    <br><br>
    <form>
    Name:
    <input type="text" name="shippingname">
    <br>
    City:
    <input type="text" name="shippingcity">
    <br>
    <input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
    <em>Check this box if Billing Address and Mailing Address are the same.</em>
    <P>
    <b>Billing Address</b>
    <br><br>
    Name:
    <input type="text" name="billingname">
    <br>
    City:
    <select name="billingcity">
    <option value="City 1">City 1</option>
    <option value="City 2">City 2</option>
    <option value="City 3">City 3</option>
    </select>
    </form>
    </TD></TR></TABLE>
    </body>
    </html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BvilleBullet
  • 201
  • 3
  • 8
  • 17
  • Is there a reason the billing city needs to be a dropdown instead of a text field? – cfs Apr 13 '13 at 01:05
  • yes because we need the users to be able to default copy data en mass if they wish but also then have the ability to change to a standard list of values in a drop down list. – BvilleBullet Apr 13 '13 at 01:21
  • 1
    `f.billingcity.value = f.shippingcity.value;`. For example, if the user types in "City 3", then the third option in the "Billing City" dropdown will selected – Ian Apr 13 '13 at 01:23
  • right but what if the drop down values have changed say from a previous year? Is there a way to set a new initial value selected not in the drop down selection? – BvilleBullet Apr 13 '13 at 01:26
  • @BvilleBullet So if the user types something in that **isn't** in the Billing dropdown, do you want it to add a new item to the billing dropdown? Or do you want it to do something else? – Ian Apr 13 '13 at 01:37
  • I would like for it to set the current value in the drop down to the value in the text field, which could or could not be already existing in the drop down menu. – BvilleBullet Apr 13 '13 at 01:40

4 Answers4

0

You need to make use of ID, and document.getElementById effectively in order to get the proper form elements and re-assign the values in the dropbox/select when the button is clicked.

<html>
<head>
<title>Untitled Document</title>
</head>

<body>
<P>
<script type="text/javascript">
<!--
function FillBilling(f) {
  if(f.billingtoo.checked == true) {

  document.getElementById("billingname").value = document.getElementById("shippingname").value;

  var optn = document.createElement("OPTION");
  optn.text = document.getElementById("shippingcity").value;;
  optn.value = document.getElementById("shippingcity").value;;;
  document.getElementById("billingcity").options.add(optn);
  }
}
// -->
</script>
<TABLE BORDER=1><TR><TD BGCOLOR="eeeeee">
<b>Mailing Address</b>
<br><br>
<form>
Name:
<input type="text" name="shippingname" id="shippingname">
<br>
City:
<input type="text" name="shippingcity" id="shippingcity">
<br>
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname" id="billingname">
<br>
City:
<select id="billingcity" name="billingcity">
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
</select>
</form>
</TD></TR></TABLE>
</body>
</html>

In order to change the select value as opposed to adding, you would use:

document.getElementById("billingcity").value=document.getElementById("shippingcity").value;
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • `getElementById` is not required at all for this question. – RobG Apr 13 '13 at 01:04
  • True, but then again it's the recommended way of doing things. – Menelaos Apr 13 '13 at 01:08
  • 1
    Recommended by who? Form controls must have a name to be successful, so you might as well take advantage of property access using an existing attribute/property rather than adding another attribute/property and calling a method. – RobG Apr 13 '13 at 01:10
  • I'll find appropriate documentation, but I remember using the "name" from the form fields has long gone out of practice. – Menelaos Apr 13 '13 at 01:16
  • I am not trying to add a drop down option, I am trying to set the selected value so how would I do that? – BvilleBullet Apr 13 '13 at 01:19
  • The `name` attribute is **required** for a form submission to work as expected. At the same time, there's no *need* to use `id`s in this situation since the form elements can just as easily be retrieved by `name` – Ian Apr 13 '13 at 01:19
  • So I guess you guys want to contest http://stackoverflow.com/questions/1513286/document-getelementbyidselage-vs-document-myforms-selage as well ? – Menelaos Apr 13 '13 at 01:21
  • @BvilleBullet You would use http://stackoverflow.com/questions/78932/how-do-i-programatically-set-the-value-of-a-select-box-element-using-javascript . And for all, is there a reason most javascript examples use document.getElementById? – Menelaos Apr 13 '13 at 01:24
  • @meewoK I was never trying to argue, I was just saying that `name` is required. At the same time, posting that link didn't help your argument at all. It has barely any votes (including the answers), therefore not giving it credibility. And it also basically argues against you. All it's really saying is using the `name` is faster, and you have to know the path to the element that way. While the OP is using `this.form`, it makes it fairly easy to navigate to the element. – Ian Apr 13 '13 at 01:24
  • @ian . What I am saying is that most of the documentation/tutorials use document.getElementById. I seem to remember using form.name 5-6 years ago+. I'm all for learning and such, and so is everyone, so can you explain why that is? Another SO post dealing with this. http://stackoverflow.com/questions/3547035/javascript-getting-html-form-values . I'm sure there are endless examples. – Menelaos Apr 13 '13 at 01:28
  • 1
    @meewoK I wish I knew why it was more popular in the past...I know `getElementById` has *always* been available. I'm being hypocritical by arguing against using `getElementById` because my solution would be to do what you suggested (although I would have never left out the `id` attribute in the first place). At the same time, the OP already had a structure where the callback was passed `this.form`. From there, it's easy to find a form element by name. In other cases, it can be difficult/misleading to have to do something like `document.forms[0].elementName` or `document.formName.elementName` – Ian Apr 13 '13 at 01:35
  • True, in this case I stuck to habit and convention. It would make a very interesting question why this shift has happened. I seem to remember something somewhere sometime (maybe) about compatibility but I'd have to search it extensively. – Menelaos Apr 13 '13 at 01:38
  • @meewoK Same here. Again, to me, it just feels wrong (for whatever reason) to use `form.element`. Since the `name` attribute is already "required" in order for the element's value be submitted to a server, I'm betting people didn't feel the need to add a whole new attribute just to select it in a different way. Another thing to think about is that the `name` attribute can be duplicated. So you can have "duplicate" forms and always reference its "First Name" textbox with `formX.firstName` instead of having to generate a **unique** `id` and reference only by that. It kind of gives it structure – Ian Apr 13 '13 at 01:42
  • @ian—getElementById *hasn't* always been available, but using control names has. IE (and many Windows browsers) didn't support getElementById until version 5. Using control names was more compatible, though that isn't an issue now. – RobG Apr 14 '13 at 22:48
  • @RobG Very true, it's hard for me to picture anything before IE 7 because I hadn't been developing then, so thats good to know. I shouldve expected something like that to be true though. Thanks for the info :) – Ian Apr 15 '13 at 00:20
0

To add a value to a select element, you need to add an option element with appropriate text and value properties. So you might do:

var select = f.billingcity;

// Create a new option element, passing values for the text and value proprties
var option = new Option(f.shippingcity.value, f.shippingcity.value);

// Append the option to the select
select.appendChild(option);

// Make the new option the selected option
option.selected = true;
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Have a look at http://stackoverflow.com/questions/1513286/document-getelementbyidselage-vs-document-myforms-selage mr Rob and the accepted answer. – Menelaos Apr 13 '13 at 01:19
0

I would recommend including jquery and then doing something like this:

function FillBilling(f) {
  if(f.billingtoo.checked == true) {
    var $firstCity = $('select option:first-child');
    $firstCity.attr('text', f.shippingcity.value);
    $firstCity.attr('value', f.shippingcity.value);
  }

This should update the first option of select to the city user enters

Also as another user suggested it'd be better practice to give the select some id (for example selectIdentificator), and then update the above code like this

var $firstCity = $('#selectIdentificator option:first-child');
Jacek Pietal
  • 1,980
  • 1
  • 18
  • 27
  • 2
    I would not recommend including a huge library like jQuery for such a simple operation. – Ian Apr 13 '13 at 01:32
0

It's a little messy, but here's my attempt at what you seem to want:

function FillBilling(f) {
    if (f.billingtoo.checked === true && f.shippingcity.value) {
        f.billingname.value = f.shippingname.value;

        var found = false;
        for (var i = 0; i < f.billingcity.options.length; i++) {
            if (f.billingcity.options[i].value.toLowerCase() === f.shippingcity.value.toLowerCase()) {
                f.billingcity.selectedIndex = i;
                found = true;
                break;
            }
        }
        if (!found) {
            var extraOption = f.billingcity.getAttribute("data-extra-option");
            if (extraOption) {
                f.billingcity.options[f.billingcity.options.length - 1].text = f.shippingcity.value;
                f.billingcity.options[f.billingcity.options.length - 1].value = f.shippingcity.value;
            } else {
                var newOption = new Option(f.shippingcity.value, f.shippingcity.value);
                f.billingcity.setAttribute("data-extra-option", "true");
                f.billingcity.appendChild(newOption);
                f.billingcity.selectedIndex = f.billingcity.options.length - 1;
            }
        } else {
            if (f.billingcity.getAttribute("data-extra-option")) {
                f.billingcity.removeChild(f.billingcity.options[f.billingcity.options.length - 1]);
                f.billingcity.selectedIndex = 0;
            }
        }
    } else {
        if (f.billingcity.getAttribute("data-extra-option")) {
            f.billingcity.removeChild(f.billingcity.options[f.billingcity.options.length - 1]);
            f.billingcity.selectedIndex = 0;
        }
    }
}

DEMO: http://jsfiddle.net/J8YrU/1/

This function is now called both for the checkbox being clicked and the Shipping City textbox value being changed.

What this function does is this:

  • If the text that's typed in the textbox matches an existing dropdown option, it selects that value
  • If the text that's typed in the textbox doesn't match an existing dropdown option, it will append a new option to the end with the user's input, and select it
  • If the text that's typed in the textbox doesn't match an existing dropdown option but there's already a new, custom option added in (from the last bullet), it just updates its text/value.

So test it, try these things:

  • Type in "City 3" in the textbox
  • Type in "asdf" in the textbox
  • Type in "asdf3" in the textbox
  • Type in "City 2" in the textbox

You can check the state of the dropdown after each thing you try and see what's happening to it. Also, you can toggle the checkbox at any point to test as well.

Ian
  • 50,146
  • 13
  • 101
  • 111