Share via


Set focus to div after button click

Question

Wednesday, February 14, 2018 1:46 PM

Hi everyone, how do I set focus to a div after a button is clicked, I have tried the following code but it's not working 

  <div class="fileUploadSection focus">
      <input id="fileUploadButton" type="submit" name="Action:Upload" value="Upload" style="display: inline-block;" class="btn btn-primary pull-right" />
  </div>

 $('#fileUploadButton.ClientID').click(function(){
        $('.focus').focus();
    })

All replies (7)

Wednesday, February 14, 2018 2:39 PM âś…Answered

The code is simply wrong and it seems you are not using the dev tools to debug.

Text View

@{
    Layout = null;
    ViewBag.Title = "Home Page";
    var scrollTo = ViewBag.ScrollTo ?? "top";
}

<div id="top" style="height:1000px;background-color:gainsboro;"></div>

<div id="fileUploadSection">
    Hello World!
</div>

<div style="height:1000px;background-color:gainsboro;"></div>

<script>
    var element_to_scroll_to = document.getElementById('@scrollTo');
    element_to_scroll_to.scrollIntoView();
</script>

The action

        public ActionResult Index()
        {
            ViewBag.ScrollTo = "fileUploadSection";
            return View();
        }

Wednesday, February 14, 2018 1:50 PM

What are you trying to do?  Maybe you want to scroll to the div?

https://stackoverflow.com/questions/3656467/is-it-possible-to-focus-on-a-div-using-javascript-focus-function


Wednesday, February 14, 2018 1:53 PM

Is it possible to scroll to a div after clicking event that will cause a page postback?


Wednesday, February 14, 2018 1:59 PM

Is it possible to scroll to a div after clicking event that will cause a page postback?

Sure, simply write a bit of JavaScript in the response that scrolls to the element.

https://stackoverflow.com/questions/3163615/how-to-scroll-html-page-to-given-anchor


Wednesday, February 14, 2018 2:11 PM

I have tried the following but still no joy

<div tabindex="-1" id="fileUploadSection1">
  <input id="fileUploadButton" type="submit" name="Action:Upload" value="Upload" style="display: inline-block;" class="btn btn-primary pull-right" />
</div>

 document.getElementById('fileUploadButton').onclick = function () {
 document.getElementById('fileUploadSection1').focus();
 };

 

Wednesday, February 14, 2018 2:30 PM

I have also tried the following, but still not working!!!!

$(document).ready(function() {
        $("#fileUploadButton.ClientID").click(function() {
            $("#Focus").val = $(this).attr('fileUploadSection1');
        });
    });

Wednesday, February 14, 2018 3:16 PM

Thanks it work great :)