我有以下表格。当地址输入字段被改变时,我想格式化长地址字段,该字段是每个地址字段的逗号分隔的连接字符串。我想从字符串中删除任何空字段并清理城市和国家/地区字段。目前我这样做:
<input id="address1" type="text" value="" name="address1" >
<input id="address2" type="text" value="" name="address2" >
<input id="city" type="text" value="" name="city" >
<input id="postcode" type="text" value="" name="postcode" >
<input id="country" type="text" value="" name="country" >
<input id="longaddress" type="text" value="" name="longaddress" >
<script>
$("#address1, #address2, #city, #country, #postcode").on('change', function (e) {
var generatedAddress = '';
if ($('#address1').val().length > 0)
generatedAddress += $('#address1').val().trim();
if ($('#address2').val().length > 0)
generatedAddress += ', ' + $('#address2').val().trim();
var city = $('#city').val();
if (city.replace(/[\s,.]+$/, '').length > 0)
generatedAddress += ', ' + city;
if ($('#postcode').val().length > 0)
generatedAddress += ', ' + $('#postcode').val().trim();
var country = $('#country').val();
if (country.replace(/[\s,.]+$/, '').length > 0)
generatedAddress += ', ' + country;
$("#longaddress).val(generatedAddress);
});
</script>
有没有更优雅的方法来实现同样的目标?