1

If I have a modal dialog which looks like the following, how can I focus the textarea after opening the dialog?

By simply adding $('#txtArea').focus(); after the code, the txtArea has focus for only a moment.

enter image description here

var popupDiv = document.createElement('div');
popupDiv.innerHTML += '<textarea id="txtArea"></textarea><br/><br/>';
popupDiv.innerHTML += '<button onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK,  $(\'#txtArea\').val());">OK</button>';


SP.UI.ModalDialog.showModalDialog({
        html: popupDiv,
        title: '',
        allowMaximize: false,
        showClose: true,
        autoSize: true,
        dialogReturnValueCallback: function () { ... }
}
2
  • are you doing this customization on sharepoint newform and editform?? Dec 11, 2015 at 13:21
  • It's on a listview webpart (regular view) via JSLink. Dec 11, 2015 at 14:24

2 Answers 2

1

It doesn't work because it takes some time for the dialog to load and be added to the DOM, but the code flow does not wait for this to happen. As far as I know there is no event that is ran after the dialog is rendered, so I came up with the following solution.

setTimeout(function() {$('#txtArea').focus();}, 200);

The timeout waits for 1/5th a second, after which the Textarea is present in the DOM.

0

Does it help if you add the focus code like this:

popupDiv.innerHTML += '<script>$("#txtArea").focus();</script>';

As far is I know the content in the modal dialog is rendered as an iFrame, so you need to embed your code in the content of the iFrame. I'm not sure if you need te reference jQuery as well to make this work.

2
  • I tried to do this, I think the script is still ran before the area is added to the page. Dec 17, 2015 at 9:56
  • And wrapping it in a $(document).ready(function () { $('#txtArea').focus() }); Does that help?
    – Oak3
    Dec 17, 2015 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.