Question

I'm building an app with knockout that's very number/input heavy. I'm refractoring my code to put everything into observableArrays so I can then bind these arrays to my HTML and all that is visible in the HTML is a template and Knockout is doing the leg-work to render all the elements inside this template.

My problem now lies with the fact my pre-existing clear input fields on focus script isn't working and I'm not entirely sure why or how to get it working.

This is the pre-existing script and is written with jQuery and I feel that there's now a conflict happening between Knockout and jQuery. Unfortunately I don't know to go about rewriting the script in Knockout.

$('input:not(.total-val)').on('focus', function() {
            var default_value = $(this).val();
            if ($(this).val() == default_value) {
                $(this).val('');
            }
            $(this).blur(function () {
                if($(this).val().length == 0) /*Small update*/
                {
                    $(this).val(default_value);
                }
            });
        });

Thanks in advance!

Was it helpful?

Solution 2

There was a conflict was with jQuery vs Knockout fighting for control over the generated inputs. I fixed this issue be refactoring the clear input script in Vanilla.

$('input:not(.total-val)').attr({'onfocus':'onFocus(this)', 'onblur':'onBlur(this)'})
        var default_value;
        onFocus = function(input) {
            default_value = input.value;
            if (input.value == default_value) {
                input.value = ''
            }
        }
        onBlur = function(input) {
            if (input.value == '') {
                input.value = default_value;
            }
        }

OTHER TIPS

You should use Knockout's hasFocus binding instead of jQuery's on('focus'). I fear that jQuery is conflicting with Knockout's binding events and causing your text to disappear on focus. Here's an example:

<p>
    Name: 
    <b data-bind="visible: !editing(), text: name, click: edit">&nbsp;</b>
    <input data-bind="visible: editing, value: name, hasFocus: editing" />
</p>
<p><em>Click the name to edit it; click elsewhere to apply changes.</em></p>

JavaScript:

function PersonViewModel(name) {
    // Data
    this.name = ko.observable(name);
    this.editing = ko.observable(false);

    // Behaviors
    this.edit = function() { this.editing(true) }
}

ko.applyBindings(new PersonViewModel("Bert Bertington"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top