Jamie Eltringham
Jamie Eltringham

Reputation: 806

Knockout Has-focus with multiple inputs

I am using knockoutjs and in my Template i have a foreach loop that will display the data it grabs from the JSON data i want to set the focus to the first input on the screen it works perfectly when there is just on input on the screen but when it gets to the second screen there are two in puts it only sets focus to the last input on the screen

here is my HTML:

<div id="section">
<span data-bind="template: { name: 'screenTemplate', foreach: screens, as: 'screen'}"></span>
<script type="text/html" id="screenTemplate">
    <!-- ko if: showFlds -->
    <!-- ko if: showNote -->
    <span data-bind="template: { name: 'fldTemplate', foreach: flds}"></span>
    <!--/ko-->
    <!--/ko-->
</script>

<script type="text/html" id="fldTemplate">
    <form>
    <span class="text" data-bind="text: fieldName"></span>
    <br/>
    <input type="text" class="inputVal" data-bind="valueUpdate: 'afterkeydown', value: inputValue, disable: (inputValue() == expectedValue()), visible:(inBool() != false)" />
    <br/>
  </form>
</script>

<div data-bind="visible:screens()[cScreen()].rdtNote() === true">
    <h2 style="color: red"><span data-bind="text: rdtNotification()[0].description()"></span></h2>
    <button data-bind="click: makeHidden">Acknowledged</button>
</div>

As shown the hasFocus is on the input in the field Template

I want to know if there is a way I can make it set focus on the first input and then move to the next input once that input is correct

If any more information is needed please ask I will do my best to provide

P.s



Current Progress: I have used jQuery

$(document).ready(function(){
  $('form').find('input[type=text],textarea,select').filter(':input:enabled:visible:first').focus();
})

But when using this it does not automatically select the next input when the screen changes is there a way to get that to work ?

Upvotes: 1

Views: 802

Answers (1)

Jamie Eltringham
Jamie Eltringham

Reputation: 806

SOLVED MY PROBLEM :

$(document).ready(function() {
 $('form').find('input[type=text],textarea,select').filter(':input:enabled:visible:first').focus();
});

$(document).keyup(function(e){
 $('form').find('input[type=text],textarea,select').filter(':input:enabled:visible:first').focus();
});

var e = $.Event("keyup", { keyCode: 13}); //"keydown" if that's what you're doing
$("body").trigger(e);

Using this I am able to set the focus to the first visible enabled input and then using jQuery to trigger the Enter Key key up I was able to make sure that the next input was always focused

Thanks @neps for the push in the right direction

Working Plunker

Upvotes: 2

Related Questions