javascript - 通过 knockout 数据绑定(bind)获取输入字段中的值

标签 javascript knockout.js knockout-2.0

我从表单字段获取输入字段的js代码如下

var DocSchedule=function(id,day,fromtime,totime,hospital,hospitalId)
{
this.id=ko.observable(id);
this.day=ko.observable(day);
this.fromtime=ko.observable(fromtime);
this.totime=ko.observable(totime);
this.hospital=ko.observable(hospital);
this.hospitalId=ko.observable(hospitalId);
}

var iter=0;


var genderOptions = ['Male', 'Female'];
var degreeOptions=['BDS','DA(Anaesthesia)','MBBS','MBBS,MD','MBBS,MD(Med)PMCH','MBBS,MD,FNB','MBBS,MS(ENT)','MD,DM,FISC','MD,MS,PhD,DSc','MDS(Oral Surgery)','MS(OPHTH),FICS','MS,DNB,MRCS(Edin),MCh(GASTRO)']
var departmentOptions=['Anesthesiology','Bio-Chemistry','Cardiac Rehab Yoga','Cardio Thoracic Surgery','Cardiology','Chest Physician','Cosmetic Plastic and Hand Surgery','Critical Care','Dental&Facio maxillary Surgery','Dermatology','Diabetology','Dietary Services','Emergency Medicine','Endocrinology','Endoscopic,Head & Neck Surgery','Endoscopy','Gastroenterology','Gastrointestinal Medicine','General Medicine','General Surgery','Geriatrics','Gynecology','Hematology','Internal Medicine','Interventional Radiology','Laboratory Medicine','Laparoscopic Surgery','Medical Oncology','Micro-Biology','Nephrology','Neuro-Surgery','Neurology','Nuclear Medicine','Nuclear Medicinee','Obstetrics and Gynecology','Ophthalmology','Orthopedics & Traumatology','Otorhinolaryngology','Pathology','Pediatric Cardiology','Pediatric Surgery','Pediatrics','Physician','Physiotherapy','Psychiatry','Pulmonology','Radio-Diagnosis','Radiology','Rheumatology','Surgical Gastro-Enterology','Surgical Oncology','Urology','Vascular Surgery']
var Doctor = function(nameParam, usernameParam){
    this.name = nameParam;
    this.username = usernameParam;
};
var doctors = [];

var Patientp = function () {
    this.id = ko.observable(idValue);
    this.name = ko.observable(nameValue);
    this.degree = ko.observable(degreeValue);
    this.gender = ko.observable(genderValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    this.username = ko.observable(usernameValue);
    this.password = ko.observable(passwordValue);
    this.email = ko.observable(emailValue);
    this.mobile = ko.observable(mobileValue);    
    this.imgFile = ko.observable(imgFileValue);
    this.imgSrc = ko.observable(imgSrcValue);
    this.imagePath=ko.observable(imagePathValue); 
    this.userid=ko.observable(useridValue); 
    this.department=ko.observable(departmentValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    //this.consultant= ko.observable(consultantValue);
    this.addSlot=function(doctor)
{


     var docSchedule=new DocSchedule();
     iter=iter+1;
     docSchedule.id(iter);
     doctor.schedules.push(docSchedule);
}


}

//idValue = 'hi';
//useridValue = 'hi';
//nameValue = 'hi';
addressValue = 'adress';
//genderValue = 'hi';
//mobileValue = 'hi';
//these fields are not available
//usernameValue = 'hi';
//passwordValue = 'hi';
//emailValue = 'hi';
imgFileValue = 'imagefileValue';
//imgSrcValue = 'ui_resources/img/profile_pic.png';
imagePathValue = 'imagePathValue';
//consultantArrValue = null;//'${currentpatient.user.name}';
//consultantValue="d1";
//var doc={};
var projectUrl=$('#projectUrl').val();

//alert(projectUrl);
/* var test=$.ajax({  
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false 
}).responseText;
console.log(test); */
$.ajax({
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false ,
    success: function (data) {
        //alert(data);
        $.each(data.doctors, function(index, currPat) {
            var doc = new Doctor(currPat.name,currPat.username);
            doctors.push(doc);
            if(currPat.userid=="${IDis}"){
           console.log(currPat.degree); 
           nameValue = currPat.name;
           usernameValue =currPat.username;
           passwordValue ="" ;
           emailValue = currPat.email;
           mobileValue = currPat.mobile;
           genderValue = currPat.gender;
           departmentValue=currPat.department;
           degreeValue=currPat.degree;
           imgSrcValue=currPat.imagePath;
           useridValue=currPat.userid;
           idValue=currPat.id;
            }
       });    
      }
});
/* var jsonobject=ko.utils.parseJson(test);
$.each(jsonobject.patients,function(i,item){
    var patient1 = new Patient(item.id, item.name, item.address, item.gender,item.consultant,item.username,"",item.email,item.mobile,"","",item.userid,item.imagePath);
    self.patients.push(patient1);       
});  */
var patp=new Patientp();
ko.applyBindings(patp);
$('#saveButton').click(function(){
    alert('savebutton');
    var testjson=ko.toJSON(patp);
    console.log(testjson);
    var formdata=new FormData();
    formdata.append("doctormetada",testjson);
    console.log(projectUrl+"updateDoctor");
    $.ajax({
        url: projectUrl+"updateDoctor", 
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (res) {
            formdata = new FormData();
                    //self.doctor(new Doctor());
                }

        });

});

查看此后answer

将我的代码更改为

var DocSchedule=function(id,day,fromtime,totime,hospital,hospitalId)
{
this.id=ko.observable(id);
this.day=ko.observable(day);
this.fromtime=ko.observable(fromtime);
this.totime=ko.observable(totime);
this.hospital=ko.observable(hospital);
this.hospitalId=ko.observable(hospitalId);
}

var iter=0;


var genderOptions = ['Male', 'Female'];
var degreeOptions=['BDS','DA(Anaesthesia)','MBBS','MBBS,MD','MBBS,MD(Med)PMCH','MBBS,MD,FNB','MBBS,MS(ENT)','MD,DM,FISC','MD,MS,PhD,DSc','MDS(Oral Surgery)','MS(OPHTH),FICS','MS,DNB,MRCS(Edin),MCh(GASTRO)']
var departmentOptions=['Anesthesiology','Bio-Chemistry','Cardiac Rehab Yoga','Cardio Thoracic Surgery','Cardiology','Chest Physician','Cosmetic Plastic and Hand Surgery','Critical Care','Dental&Facio maxillary Surgery','Dermatology','Diabetology','Dietary Services','Emergency Medicine','Endocrinology','Endoscopic,Head & Neck Surgery','Endoscopy','Gastroenterology','Gastrointestinal Medicine','General Medicine','General Surgery','Geriatrics','Gynecology','Hematology','Internal Medicine','Interventional Radiology','Laboratory Medicine','Laparoscopic Surgery','Medical Oncology','Micro-Biology','Nephrology','Neuro-Surgery','Neurology','Nuclear Medicine','Nuclear Medicinee','Obstetrics and Gynecology','Ophthalmology','Orthopedics & Traumatology','Otorhinolaryngology','Pathology','Pediatric Cardiology','Pediatric Surgery','Pediatrics','Physician','Physiotherapy','Psychiatry','Pulmonology','Radio-Diagnosis','Radiology','Rheumatology','Surgical Gastro-Enterology','Surgical Oncology','Urology','Vascular Surgery']
var Doctor = function(nameParam, usernameParam){
    this.name = nameParam;
    this.username = usernameParam;
};
var doctors = [];

var Patientp = function () {
    this.id = ko.observable(idValue);
    this.name = ko.observable(nameValue);
    this.degree = ko.observable(degreeValue);
    this.gender = ko.observable(genderValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    this.username = ko.observable(usernameValue);
    this.password = ko.observable(passwordValue);
    this.email = ko.observable(emailValue);
    this.mobile = ko.observable(mobileValue);    
    this.imgFile = ko.observable(imgFileValue);
    this.imgSrc = ko.observable(imgSrcValue);
    this.imagePath=ko.observable(imagePathValue); 
    this.userid=ko.observable(useridValue); 
    this.department=ko.observable(departmentValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    //this.consultant= ko.observable(consultantValue);
    this.addSlot=function(doctor)
{


        mm = doctor
        console.log("this", doctor);
        var docSchedule = new DocSchedule();
        iter++;
        docSchedule.id(iter);
        this.schedulers().push(docSchedule);
}


}

//idValue = 'hi';
//useridValue = 'hi';
//nameValue = 'hi';
addressValue = 'adress';
//genderValue = 'hi';
//mobileValue = 'hi';
//these fields are not available
//usernameValue = 'hi';
//passwordValue = 'hi';
//emailValue = 'hi';
imgFileValue = 'imagefileValue';
//imgSrcValue = 'ui_resources/img/profile_pic.png';
imagePathValue = 'imagePathValue';
//consultantArrValue = null;//'${currentpatient.user.name}';
//consultantValue="d1";
//var doc={};
var projectUrl=$('#projectUrl').val();

//alert(projectUrl);
/* var test=$.ajax({  
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false 
}).responseText;
console.log(test); */
$.ajax({
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false ,
    success: function (data) {
        //alert(data);
        $.each(data.doctors, function(index, currPat) {
            var doc = new Doctor(currPat.name,currPat.username);
            doctors.push(doc);
            if(currPat.userid=="${IDis}"){
           console.log(currPat.degree); 
           nameValue = currPat.name;
           usernameValue =currPat.username;
           passwordValue ="" ;
           emailValue = currPat.email;
           mobileValue = currPat.mobile;
           genderValue = currPat.gender;
           departmentValue=currPat.department;
           degreeValue=currPat.degree;
           imgSrcValue=currPat.imagePath;
           useridValue=currPat.userid;
           idValue=currPat.id;
            }
       });    
      }
});
/* var jsonobject=ko.utils.parseJson(test);
$.each(jsonobject.patients,function(i,item){
    var patient1 = new Patient(item.id, item.name, item.address, item.gender,item.consultant,item.username,"",item.email,item.mobile,"","",item.userid,item.imagePath);
    self.patients.push(patient1);       
});  */
//var patp=new Patientp();
//ko.applyBindings(patp);
function vm() {
            var self = this;
            self.person = new Patientp();
            self.schedule = new DocSchedule();
            self.schedules = ko.observableArray([new DocSchedule(iter)]);

            self.addSlot = function () {
                console.log(self.schedules.length);
                iter++;
                var docSchedule = new DocSchedule(iter);
                self.schedules.push(docSchedule);
            };

            self.removeSlot = function () {
                console.log('removed');
                self.schedules.remove(this);
            }
        };
        var viewModel = new vm();
        ko.applyBindings(viewModel, document.getElementById('addDoctorSchedules'));
$('#saveButton').click(function(){
    alert('savebutton');
    var testjson=ko.toJSON(self.person);
    console.log(testjson);
    var formdata=new FormData();
    formdata.append("doctormetada",testjson);
    console.log(projectUrl+"updateDoctor");
    $.ajax({
        url: projectUrl+"updateDoctor", 
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (res) {
            formdata = new FormData();
                    //self.doctor(new Doctor());
                }

        });

});

所以现在我没有在表单字段中获得任何值,甚至在浏览器控制台中也没有错误。

enter image description here

任何人都可以指出我所做的错误吗?

最佳答案

这是因为ajax请求到viewmodel Patientp的数据初始化,

尝试将 Patientp 更改为此。

HTML

<table id="test">
    <tr>
        <td>Name</td>
        <td><input type="text" name="name" data-bind='value: person.name' /></td>
    </tr>
    <tr>
        <td>Department</td>
        <td><select data-bind='options: departmentOptions, optionsText: departmentOptions, optionsCaption: "Select...", value: person.department'> </select></td>
    </tr>
    <tr>
        <td>Gender</td>
        <td><select data-bind='options: genderOptions, optionsText: genderOptions, optionsCaption: "Select...", value: person.gender'> </select></td>
    </tr>
    <tr>
        <td>Degree</td>
        <td><select data-bind='options: degreeOptions, optionsText: degreeOptions, optionsCaption: "Select...", value: person.degree'> </select></td>
    </tr>
    <tr>
        <td>UserName</td>
        <td><input type="text" name="name" data-bind='value: person.username' /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><input type="text" name="name" data-bind='value: person.password' /></td>
    </tr>
</table>

javaScript

var Patientp = function () {
    this.id = ko.observable('');
    this.name = ko.observable('');
    this.degree = ko.observable('');
    this.gender = ko.observable('');
    this.username = ko.observable('');
    this.password = ko.observable('');
    this.email = ko.observable('');
    this.mobile = ko.observable('');
    this.imgFile = ko.observable('');
    this.imgSrc = ko.observable('');
    this.imagePath = ko.observable('');
    this.userid = ko.observable('');
    this.department = ko.observable('');
}

然后设置如下值:

if (currPat.userid == "${IDis}") {
    console.log(currPat.degree);
    pat.name = currPat.name;
    pat.username = currPat.username;
    pat.password = currPat.password;
    pat.email = currPat.email;
    pat.mobile = currPat.mobile;
    pat.gender = currPat.gender;
    pat.department = currPat.department;
    pat.degree = currPat.degree;
    pat.imagePath = currPat.imagePath;
    pat.userid = currPat.userid;
    pat.id = currPat.id;
}

这是 Demo

关于javascript - 通过 knockout 数据绑定(bind)获取输入字段中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23443824/

相关文章:

javascript - 将 true/false 绑定(bind)到 Knockout JS 中的单选按钮

jquery - 如何使用phonegap在拨号框中分配电话号码?

javascript - 检查给定日期是否在工作周内(周一至周五)

javascript - JS 构造函数/原型(prototype)与类的语义名称

asp.net-mvc - Internet Explorer 中的 knockout 验证错误?

javascript - 追踪 knockout 事件

javascript - 是否有适合 Javascript 1.7 尤其是 Firefox 扩展的编译器/压缩器库?

javascript - 如何调整 jQuery 动画让元素停留在中间?

ajax - 在 AJAX 调用后将新的 DOM 元素绑定(bind)到 View 模型

c# - ASP.Net WebAPI Post 方法显示空值