0
votes

I'm having issues accessing data from html.

How it works: The user will pick a radio button and the code from the KnockoutJS observables will update "data-bind="text: radioFrom" with the value of the selected radio button. I want to print out the string stored in the variable "data-bind="text: radioFrom" to the console.

I've tried doing this, but I keep getting errors or, more frequently, it just outputs the variable as "undefined". How can I print this to the console (or in an alert)?

My attempts

---------------------------------------------------
var jsonRadioFrom = JSON.stringify(self.radioFrom);         
console.log(jsonRadioFrom);
---------------------------------------------------
console.log(self.radioFrom)
---------------------------------------------------
console.log(self.radioFrom.name)
---------------------------------------------------

These are the radio buttons

<td class="label">From:</td>
<td>
    <label><input type="radio" value="Dev1" data-bind="checked: radioFrom" />Dev [devName1]</label>
    <label><input type="radio" value="Dev2" data-bind="checked: radioFrom" />Dev2 [devName2]</label>
</td>

This holds the value of the selected radio button

<tr>
    <td class="label">From:</td>
    <td data-bind="text: radioFrom"></td>
</tr>

This is part of my Javascript/KnockoutJS

<script>
    var TabViewModel = function(){
        var self = this;
        self.radioFrom = ko.observable("Dev1"); 
    };
    ko.applyBindings(new TabViewModel());
</script>
1

1 Answers

2
votes

ko.dataFor() gets KO view model bound with given HTML element.

ko.dataFor($("body")[0]).radioFrom()

Another option is to assign instance of TabViewModel to global variable, so it gets accessible from console with autocomplete

<script>
    var TabViewModel = function(){
        var self = this;
        self.radioFrom = ko.observable("Dev1"); 
    };
    window.viewModel = new TabViewModel();
    ko.applyBindings(window.viewModel);
</script>

Now following will work:

viewModel.radioFrom()