Javascript 条件表单疑难解答
我是Javascript新手,尝试使用bootstrap和JQuery构建条件表单。我真的很感谢你的帮助,因为我一天大部分时间都在做这件事,但都没有用 当名称为Javascript 条件表单疑难解答,javascript,Javascript,我是Javascript新手,尝试使用bootstrap和JQuery构建条件表单。我真的很感谢你的帮助,因为我一天大部分时间都在做这件事,但都没有用 当名称为AppointmentType的select字段的值为骨科或风湿病时,我正试图显示id为医师的div(以及后续字段)。这是你的电话号码 以下是我的javascript: $( document ).ready(function() { //wait until body loads //Inputs that determine
AppointmentType
的select字段的值为骨科
或风湿病
时,我正试图显示id为医师的div
(以及后续字段)。这是你的电话号码
以下是我的javascript:
$( document ).ready(function() { //wait until body loads
//Inputs that determine what fields to show
var appttype = $('#secureform input:select[name=AppointmentType]');
var physician = document.getElementById("physician");
appttype.change(function(){ //when the Appointment Type changes
var value=this.value;
physician.addClass('hidden'); //hide everything and reveal as needed
if (value === 'Orthopedic' || value === 'Rheumatology'){
physician.removeClass('hidden'); //show doctors
}
else {}
});
});
这些行将导致错误(您应该在devtools控制台中看到):
纠正这些行,它应该会工作
如果有帮助,我会这样写:
$( document ).ready(function () {
//Inputs that determine what fields to show
var apptType = $('#secureform select[name="AppointmentType"]'); // dropped the `input:` part
var physician = document.getElementById('physician');
physician.classList.add('hidden'); //hide this initially, outside the change handler
apptType.change(function () { // when the Appointment Type changes
var value = $(this).val().toLowerCase(); // leave case-sensitivity out of it.
var showables = [ // using an array as I prefer using a simple `indexOf` for multiple comparisons
'orthopedic',
'rheumatology',
];
var isShowable = showables.indexOf(value) > -1;
physician.classList.toggle('hidden', !isShowable);
// or, the jQuery equivalent:
// $(physician).toggleClass('hidden', !isShowable);
});
});
您的选择器不正确:
var appttype = $('#secureform input:select[name=AppointmentType]');
// this should be
var appttype = $('#secureform select[name=AppointmentType]');
此外,您还将jquery与vanillaJS混合使用。你在这里使用的是香草js
var physician = document.getElementById("physician");
医生现在是一个dom对象,而不是jquery对象。您应该改为使用此选项:
var physician = $("#physician");
此外,您应该更换
var value=this.value;
用这个
var value= $(this).val();
当您混合使用jQuery和DOM时,您会遇到这些问题<代码>医师
没有控制台应该告诉您的添加类
/移除类
。为什么?因为它是DOM而不是jQuery对象。
var value= $(this).val();