所以基本上我希望在滿足特定要求時改變“租船”的價格。如果用戶選擇一個作業日的日期,它將從輸入欄位中獲取值,價格將為每小時 10 美元。如果是星期六,價格將是每小時 15 美元,如果是星期天,價格將是每小時 20 美元。用戶最多可以租用 10 小時,他們將在底部獲得總價。
我現在只有輸入欄位的 HTML 代碼,我什至不知道如何開始 JavaScript 部分。因此,如果有人可以教如何開始,將不勝感激!
<div id="main">
<label for="which_date">Which date do you want to rent?</label>
<input type="date" id="which_date_input" min="2022-05-02">
<button id="submit">Submit</button>
<label for="total_hours">How many hours do you want to rent? (Max 10 hours)</label>
<input type="number" id="total_hours_input" placeholder="0" min="1" max="10">
<p id="result"></p>
如果我想要的解釋難以理解,我很抱歉,我是 JavaScript 的初學者。
謝謝
uj5u.com熱心網友回復:
你可以試試這樣的...
function getPrice() {
const whichDate = new Date(document.getElementById("which_date_input").value);
const totalHours = document.getElementById("total_hours_input").value;
let perHour = 10;
if (whichDate.getDay() === 6) {
perHour = 15;
}
if (whichDate.getDay() === 0) {
perHour = 20;
}
document.getElementById("result").innerText = "Total price: $" totalHours * perHour;
}
<div id="main">
<label for="which_date">Which date do you want the ticket for?</label><br>
<input type="date" id="which_date_input" min="2022-05-02"><br>
<label for="total_hours">How many hours do you want to rent? (Max 10 hours)</label><br>
<input type="number" id="total_hours_input" placeholder="0" min="1" max="10">
<button id="submit" onclick="getPrice()">Submit</button><br>
<p id="result"></p>
</div>
uj5u.com熱心網友回復:
這應該可以很好地表明您正在嘗試做什么。您可以使用該input
事件target.value
來獲取值。我value
通過解構得到: const {value} = target
它類似于target.value
.
如果您不想使用實時結果,您可以使用類似submitButton.addEventListener('submit', ...
設定 submitButton via 的東西querySelector
。target.value
但是如果您決定這樣做,您仍然需要從“小時”輸入元素中讀取相同的內容。
// Do something with the results
const someAction = (amount) => {
console.log(`The amount is: £${amount}`)
}
// Get the input element
const totalHoursInput = document.querySelector("#total_hours_input")
// Listen to the input event
totalHoursInput.addEventListener("input", ({
target
}) => {
// Get the day name
const day = new Date().toLocaleString('en-us', {
weekday: 'long'
}).toLocaleLowerCase()
const { value } = target // The input value
// Determine the correct rate
let rate = 10 // Weekday default
if (day === "saturday") {
rate = 15
} else if (day === "sunday") {
rate = 20
}
// do something with the rate x value
someAction(rate * value)
})
uj5u.com熱心網友回復:
<label for="which_date">Which date do you want the ticket for?</label>
<input type="date" id="which_date_input" value="" min="2022-05-02">
<button id="submit" onclick="getDate()">Submit</button>
<p id="result"></p>
<script>
function getDate() {
var x = document.getElementById("which_date_input").value;
document.getElementById("result").innerHTML = x;
}
</script>
現在使用您要在 var X 上應用的條件。取貨日期將存盤在 x 中,您可以將其用于您的條件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470808.html
標籤:javascript html 日期 输入字段
下一篇:新列:當日期=日期時傳輸值