[英]JavaScript and getting the value of radio button
我嘗試使用javascript創建在線計算表格,除單選按鈕外,其他一切正常。
場景:
x(select list) =
item1 - value="11.2"
item2 - value="7.6"
item3 - value="7"
y=(input number)
z=(input number)
coverkind=(radio button)
if 1 selected >> coverkind = z*800
if 2 selected >> coverkind = ((y/16)+1)*8*z
totalprice= (x*y*z)+(1000*z)+coverkind
到目前為止,我的工作是:
<html>
<head>
<script type="text/javascript">
function getselectionPrice() {
var elt = document.getElementById("selectionone");
var selectionPrice = elt.options[elt.selectedIndex].value;
var y = document.getElementById("y").value;
var z = document.getElementById("z").value;
var ser = (selectionPrice * y * z);
var dz = z*1000;
var coverkind = document.getElementById("cover").value;
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}
var finalPrice = ser + dz;
document.getElementById("totalPrice").value = finalPrice;
}
</script>
</head>
<body>
<div>
<form action="" id="calcform" onsubmit="return false;">
<div>
<div>
<fieldset>
<label>select</label>
<select id="selectionone" name='selectionone' onChange="getselectionPrice()">
<option value="11.2">1</option>
<option value="7.6">2</option>
<option value="7">3</option>
</select>
<br/>
<p>y
<input type="text" id="y" onchange="getselectionPrice()" />
</p>
<p>z
<input type="text" id="z" onchange="getselectionPrice()" />
</p>
<label>cover</label>
<input type="radio" name="cover" value="hard" />hard
<br />
<br>
<input type="radio" name="cover" value="soft" />soft
<br>
<br>
<br/>The new calculated price:
<INPUT type="text" id="totalPrice" Size=8>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="getselectionPrice()" />
</div>
</form>
</div>
</body>
</html>
如果我從js中刪除coverkind,其余的工作正常。 我搜尋有關通過單選按鈕獲取價值的信息,但沒有發現與這種情況非常相關的東西。 螢火蟲錯誤面板:
TypeError:document.getElementById(...)為null var coverkind = document.getElementById(“ cover”)。value;
如果可以使用jQuery,則可以在一行中獲取選中的單選按鈕的值。
var Val = $("input[name=cover]:checked").val();
您可以根據需要使用輸出標簽,也可以使用其他方式輸出。 (例如<p>
元素)。 只需確保在Javascipt中為您要訪問的任何內容提供一個“ id”值即可。
您需要創建一個新文件,並將其命名為“ script.js”。 Google如何將此腳本包含在html文檔中。
您需要在腳本中使用的一些東西:
document.getElementById(str)
返回一個對象,該對象表示id為'str'的html元素
parseFloat(str)
接受字符串'str'並返回float值
.value
這是包含文本值的輸入文本框對象的讀/寫屬性
.checked
..和輸入單選按鈕對象的屬性。
當您碰壁時,請參考出色的Google;)將所有內容放在一起,您應該走在正確的軌道上。
這是您的問題的解決方案。
首先給您的單選按鈕提供相同的ID。 選中的屬性將告訴您是否選擇了元素:
<input type="radio" id="cover" name="cover" value="hard" checked="checked" />hard
<br />
<br>
<input type="radio" id="cover" name="cover" value="soft" />soft
在JavaScript函數中,您可以獲得它。
var coverkind = null;
if (document.getElementById('cover').checked)
{
coverkind = document.getElementById('cover').value;
}
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.