当选择单选按钮标题值的单选按钮时,应将其添加到输入文本框中

时间:2018-04-08 12:16:23

标签: javascript html knockout.js

http://jsfiddle.net/LkqTU/45756/

<div class='liveExample'>   
<input type="radio" name="gender" value="Mr." checked>Mr.
    <input type="radio" name="gender" value="Mrs.">Mrs.
    <p>First name: <input data-bind='value: firstName' /></p> 

</div>



// Here's my data model
var ViewModel = function(gender) {

    this.lastName = ko.observable(gender);

    this.firstName = ko.computed(function() {

        return this.gender() +  this.firstname();
    }, this);
};

当点击单选按钮时,先生和夫人应该在名字的文本框前添加。

3 个答案:

答案 0 :(得分:1)

这应该有效:

&#13;
&#13;
var ViewModel = function(gender) {

  this.lastName = ko.observable(gender);

  this.firstName = ko.computed(function() {

    return this.gender() + this.firstname();
  }, this);
};


function putMr() {
  document.getElementById('textField').value = 'Mr.';
}

function putMrs() {
  document.getElementById('textField').value = 'Mrs.';
}
&#13;
<input type="radio" name="gender" value="Mr." checked onclick="putMr()">Mr.
<input type="radio" name="gender" value="Mrs." onclick="putMrs()">Mrs.


<p>First name: <input data-bind='value: firstName' id="textField" /></p>
&#13;
&#13;
&#13;

我在单选按钮上使用onclick方法,然后将一个JS函数耦合到它上面附加前缀。

答案 1 :(得分:0)

我已在“http://jsfiddle.net/LkqTU/45804/”更新了您的代码。请看。

将js更改为:

function setGender(obj){
document.getElementById('set_value').value = obj.value;
console.log(obj.value);

}

并输入字段为:

<p>First name: <input data-bind='value: firstName' id="set_value"/></p> 

http://jsfiddle.net/LkqTU/45804/

答案 2 :(得分:0)

您使用knockout标记标记了此问题。但你的小提琴是错误的。

我更新了您的视图模型:

a)this.lastName = ko.observable(gender);应为this.gender = ko.observable(gender);

b)我将this.firstName = ko.computed ...更改为可观察的this.firstName = ko.observable('');

你忘了申请绑定:ko.applyBindings(new ViewModel('m')); 另外,你需要添加jQuery,因为Knockout需要它。

那是:

var ViewModel = function(gender) {

    this.gender = ko.observable(gender);
    this.firstName = ko.observable('');

    this.fullData = ko.computed(function() {           
        return this.gender() + ' ' + this.firstName();
    }, this);
};

ko.applyBindings(new ViewModel('m'));

<div class='liveExample'>   
    <input type="radio" name="gender" value="Mr." checked>Mr.
    <input type="radio" name="gender" value="Mrs.">Mrs.
    <p>First name: <input data-bind='value: firstName' /></p> 

</div>

现在,更改单选按钮以使用checked binding

<input type="radio" name="gender" value="Mr."  data-bind="checked: gender"> Mr.
<input type="radio" name="gender" value="Mrs." data-bind="checked: gender"> Mrs.

这样,当您单击单选按钮时,您的视图模型会更新。

最后要做的是显示gender添加<span data-bind="text:gender"></span>的价值:

<p>First name: <span data-bind="text:gender"></span><input data-bind='value: firstName' /></p> 

这是updated fiddle