Home > Software engineering >  How do I add jQuery to a Blazor server app?
How do I add jQuery to a Blazor server app?

Time:06-20

I'm attempting to add some jQuery to a Blazor server app. Specifically being able to autocomplete an InputText field on a form (where id = 'CompanyName') which is on a razor page (CreateNote.razor). When I run the app, autocomplete doesn't work. I've added the alert line to test if that executes and that works fine.

_Layout.cshtml:

...
</head>
    <link href="TelephoneNotes.styles.css" rel="stylesheet" />

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script>

    <link href="https://tofsjonas.github.io/sortable/sortable.css" rel="stylesheet" />
    <script src="https://tofsjonas.github.io/sortable/sortable.js"></script>

    <script type="text/javascript">$(function () {
            $("#companyName").autocomplete({
                source: ["Apple", "Google", "Facebook"],
                minLength: 3
            })

    $(document).ready(function () {
        alert("test");
    });

        })</script>
    <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>

CreateNote.razor:

<EditForm Model="@newNote" OnSubmit="@InsertNote">
...
    <div  style="padding-top: 5px;">
        <label for="company" >
            Company:
        </label>
        <div >
            <InputText id="companyName"  placeholder=""
                       @bind-Value="newNote.CompanyName" />
        </div>
    </div>
...
</EditForm>

CodePudding user response:

Put your javascript at the end of the body tag. The current location you've put it $("#companyName") will be null. The component has to be loaded before your javascript executes.

<html>
<body>

<Your Components will be here>

 <script type="text/javascript">$(function () {
            $("#companyName").autocomplete({
                source: ["Apple", "Google", "Facebook"],
                minLength: 3
            })

    $(document).ready(function () {
        alert("test");
    });

        })</script>
<body>
</html>

CodePudding user response:

Blazor does not understand the querry selector '$', you need to replace it with keyword

document

CodePudding user response:

You can not use Js like this in Blazor.

What is $( document ).ready() {}?
It means that the code inside this scope {} will render just and only once the page DOM is ready for JS code to execute.

When is the DOM ready in Blazor?
In most cases you have to execute the JS code in the bult-in OnAfterRender function because in this point you will be sure that DOM is complete and you can use JS to manipulate the front-end.

What is the best way to execute JS functions?

  1. Create a separate file(MyJs.js) for Js in the wwwroot folder and add your JS functions there.

    function CompleteFormControls ()
    {
      $("#companyName").autocomplete({
      source: ["Apple", "Google", "Facebook"],
      minLength: 3
    }
    
  2. Create a class file to represent your functions in MyJs.js file:

    puplic statis class JsHelper
    {
     [DebuggerHidden]// tell VS Don't debug this function
     puplic statis aasync ValueTask CompleteFormControlsAsync(this IJSRunTime)
     {
      await js.InvokeVoidAsync("CompleteFormControls");
     }
    } 
    
  3. Inject IJSRuntime in your razor page:

    [Inject] private IJSRuntime Js {get; set;}
    protected override Task OnAfterRenderAsync(bool firstRender)
    {
      if(firstRender)
      {
        await Js.CompleteFormControlsAsync();
      }
    }
    

Note: You can also replace OnAfterRenderAsync and use some event like Click event, because in this case you are sure that the DOM has also completed rendering.

  • Related