As the user enters their address details I am collecting the data and creating a single line to display. I can set the text inputs ok with a line like this var address1 = document.address.address1.value; but the towns are a select box with the values being IDs and the text being the value I need to collect. For the text inputs I use onkeyup="autoAddress();" and the select I use onchange="autoAddress();"

The line var town = document.address.town_id.value returns me the ID but I need the text

<input type="text" name="address1" id="address1" data-rule-required="true" class="form-control" value="{$form_data.address1}" onkeyup="autoAddress();">
<input type="text" name="address2" id="address2" class="form-control" value="{$form_data.address2}" onkeyup="autoAddress();">
<select class="form-control chosen" name="town_id" id="town_id" data-rule-required="true" data-placeholder="Choose a town" onchange="autoAddress();">
    <option value=""></option>
    {foreach $towns as $town}
    <option value="{$town.id}" {if $town.id eq $form_data.town_id}selected="selected"{/if}>{$town.town_name} {if $town.region_name}, {$town.region_name}{/if}</option>
    {/foreach}
</select>

function autoAddress(){
    var house_number = document.address.house_number.value;
    var address1 = document.address.address1.value;
    var address2 = document.address.address2.value;
    var town = document.address.town_id.value;
    var postcode = document.address.postcode.value;
}
有帮助吗?

解决方案

var town = document.address.town_id.options[document.address.town_id.selectedIndex].innerHTML;

其他提示

you should try this.

function autoAddress(){
    var house_number = document.address.house_number.value;
    var address1 = document.address.address1.value;
    var address2 = document.address.address2.value;
    var town = document.address.town_id.options[document.address.town_id.selectedIndex].text;
    var postcode = document.address.postcode.value;
}

You may try something like this (Example)

HTML: Change your onchange notice I've added this as functions's argument

<select onchange="autoAddress(this);"></select>

JS:

function autoAddress(el)
{
    var txt = el.options[el.selectedIndex].innerHTML;
    alert(txt);
}

Try '.text' in place of '.value'. E.g:

var townElement = document.getElementById('town_id');
var townText = townElement[townElement.selectIndex].text;

Try this:

document.getElementById('town_id').options[document.getElementById('town_id').selectedIndex].text;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top