Laravel:如何让HTML下拉框提交自定义数值到数据库?
Got it, let's sort this out for you! The core issue here is separating the value you want to save to your database (1 for Watch, 2 for Bracelet) from the price you want to display to users. Here are two simple, reliable approaches:
Approach 1: Use Data Attributes (Cleanest & Recommended)
Modify your <option> elements to set the database-friendly ID as their value, and store the price in a data-price attribute. This keeps your form submission and frontend display logic cleanly separated.
Updated HTML:
<select id="select_item" class="form-control" name="sample_collection_type"> <option value="">Choose your item</option> <option value="1" data-price="4500">Watch</option> <option value="2" data-price="3000">Bracelet</option> </select> <input type="text" name="test_amount" class="form-control input_price" readonly>
Updated JavaScript:
$('#select_item').on('change', function() { // Grab the selected option to access both its value and data attribute const selectedOption = $(this).find('option:selected'); // Set the input to show the price from the data attribute $('.input_price').val(selectedOption.data('price')); });
How this works: When the form submits, the sample_collection_type field will send 1 or 2 directly to your backend (perfect for database storage), while the input still displays the correct price to the user. No extra hidden fields needed!
Approach 2: Use a Value Mapping (If You Can't Modify Original HTML)
If you can't change the existing <option> values, create a mapping object in JavaScript to convert the price values to your desired database IDs. You'll need a hidden input to store the converted ID for form submission.
Original HTML (Plus Hidden Input):
<select id="select_item" class="form-control" name="sample_collection_type"> <option value="">Choose your item</option> <option value="4500">Watch</option> <option value="3000">Bracelet</option> </select> <input type="text" name="test_amount" class="form-control input_price" readonly> <!-- Hidden input to store the database ID --> <input type="hidden" name="db_collection_id" id="hidden_db_id">
Updated JavaScript:
// Map price values to their corresponding database IDs const priceToIdMap = { '4500': '1', '3000': '2' }; $('#select_item').on('change', function() { const selectedPrice = $(this).val(); // Update the visible price input as before $('.input_price').val(selectedPrice); // Set the hidden input to the mapped database ID $('#hidden_db_id').val(priceToIdMap[selectedPrice] || ''); });
How this works: When the form submits, your backend should read the value from db_collection_id (instead of the original sample_collection_type) to get the 1 or 2 you want to store.
Quick Backend Note
Whichever approach you choose, make sure your backend code is set to accept the correct field name:
- For Approach 1: Use
sample_collection_type - For Approach 2: Use
db_collection_id
内容的提问来源于stack exchange,提问作者Tia Mat

