Skip to content
Advertisement

Changing an Input value in Blazor by javascript doesn’t change it’s binded property value

I’m building a website using app.net core 3.1 with blazor. In one of my components I have :

<input @bind="Message" type="text" id="input-message"/>

Message is just a string property.

and I have javascript:

document.getElementById('input-message').value = 'some text';

The problem is after running the above js, <input> value changes but Message value doesn’t, and of course if I type or paste something inside <input> , Message value changes too.

Advertisement

Answer

Apparently changing <input> value or any other changes in DOM by javascript doesn’t change State, so blazor won’t re-render the component. Even calling StateHasChanged(); manually in your razor page won’t work.

To get this done, you just have to trigger the same DOM events that occur if the user modifies the <input> normally, just like below:

var myElement = document.getElementById('input-message');
myElement.value = 'some text';
var event = new Event('change');
myElement.dispatchEvent(event);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement