简体   繁体   中英

Rails: after rendering partial with Ajax, manipulating that partial with JS

On my app, users click a button that makes a text field appear via ajax.

I want to focus on that text field after it appears.

$("#my-textfield").focus() does not work when in my js.erb file, but works fine in the console. I also tried it with a setTimeout to no avail.

When I do document.getElementById('my-textfield').focus(); I get "cannot focus on null".

Do I need to "reload" the DOM somehow after loading a partial via ajax?

You could listen for the event DOMNodeInserted with .on(). It's not widely supported yet, and I've never used it, but it looks like it may work for what you're trying to do.

I haven't really done this but you can try

$function() {
  $("#my-textfield").load(function() {
    $(this).focus();
  });
});

to make sure it has loaded first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM