In e-commerce websites, a shipping address selection feature needs to be implemented. Here are two traditional approaches.
Method 1: Using Ajax + CSS + jQuery
HTML file
<br />
<h2 id="address_select">Select Shipping Address</h2>
<hr />
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Phone</th>
<th>Province</th>
<th>City</th>
<th>District</th>
<th>Street</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<tr class="address">
<td>1</td>
<td>yongqiang</td>
<td>18910008000</td>
<td>Inner Mongolia</td>
<td>Ulanqab</td>
<td>Jining</td>
<td>Building 15, Unit 1, Room 203, Some Complex</td>
<td><a href="/addresses/1">Show</a></td>
<td><a href="/addresses/1/edit">Edit</a></td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/addresses/1">Destroy</a></td>
</tr>
<tr class="address">
<td>2</td>
<td>lily</td>
<td>18910002000</td>
<td>Hebei</td>
<td>Shijiazhuang</td>
<td>Yuhua</td>
<td>22 Yuxiang Street</td>
<td><a href="/addresses/2">Show</a></td>
<td><a href="/addresses/2/edit">Edit</a></td>
<td><a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/addresses/2">Destroy</a></td>
</tr>
</tbody>
</table>
CSS file. Style changes depend on adding and removing classes.
.selected {
color: white;
background-color: skyblue;
}
JS file. Get the selected ID, toggle styles.
// check.js
$(function() {
// address_id gets the id of address which is selected by user.
var address_id;
// get address_id
$(".address").click(function(event) {
//console.log($(this).children('td').eq(0).text())
$(".address").removeClass('selected')
$(this).addClass('selected');
address_id = $(this).children('td').eq(0).text();
});
// for debug
$("#address_select").click(function(event) {
/* Act on the event */
alert(address_id);
});
});
Method 2: Using HTML’s Native Select
A simpler approach for address selection is to directly use the HTML built-in select element. This avoids unnecessary issues introduced by JavaScript processing.
Comparison of the Two Approaches
Method 1 is more complex to implement but offers better visual presentation and user experience, with high customizability, though it introduces unpredictable JavaScript issues. There are still some implementation problems: after switching controllers, clicking the address becomes unresponsive. JD.com likely uses this approach.
Method 2 is easy to implement, has virtually no dependencies, and uses native HTML.
My choice: when functionality is sufficient, use the native HTML select method.
Comments