我正在尝试验证表单。
我要做的是通过验证选项 显示文字而不是选项值来验证表单,因为选项值为int
示例:
<option value="selectcard">Please select</option>
如果用户点击提交表单,则应验证选项显示是否显示请选择 无论选项值是什么。
无效的代码
function fun(){
$('#cardtype').change(function () {
var sel = $('option:selected', this).text();
if (sel == "Please select") {
$('.showotherpDescription').show();
} else {
}
});
}
无效:http://jsfiddle.net/f5hxpo7g/2/
还包括基于选项值验证表单的常规工作示例
根据选项值进行验证 http://jsfiddle.net/f5hxpo7g/1/
请让我知道我做错了什么。
提前致谢。
答案 0 :(得分:1)
你的功能应该是这样的:
function fun()
{
var ddl = document.getElementById("cardtype");
var valor = ddl.options[ddl.selectedIndex].text;
if (valor == "--- Please select ---")
{
alert("Please select a card type");
}
}
答案 1 :(得分:0)
我修好了,你应该使用这个JS:
$(function () {
$('#subbutton').click(function () {
if ($('#cardtype option:selected').text() === "Please select")
{
alert("PLEASE SELECT");
}
});
});
从按钮中删除onclick="..."
,您不需要它。同时添加id="subbutton
。
答案 2 :(得分:0)
我检查了您引用的jsfiddle并稍微修改它以使其正常工作,您可以看到它here。
您提供的代码存在问题,IMO:
查看我提供的jsfiddle中的代码,如果您需要更多信息,请告诉我。
供参考,以下是我使用的代码:
HTML:
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select>
<input type="button" onclick="fun()" value="click here">
JS:
function fun(){
var cmb = document.getElementById('cardtype');
var sel = cmb.options[cmb.selectedIndex].text;
if (sel == "--- Please select ---") {
alert('Please select a different option');
//$('.showotherpDescription').show();
} else {
}
}
}