To display data from your HTML form in MATLAB using the "uihtml" component, you need to ensure that the data is correctly passed from the HTML form to MATLAB and then handled appropriately.
There are a few issues in your current setup that need to be addressed:
1. You need to ensure that the data is correctly passed from the HTML to the MATLAB environment. Your JavaScript code should correctly format the data and trigger the "DataChangedFcn" callback in MATLAB.
2. When passing data from JavaScript to MATLAB, ensure it's in a format MATLAB can understand, such as JSON.
Here's how you can modify your code:
MATLAB Code
% Create a UI figure
fig = uifigure;
fig.Position = [500 500 490 180];
% Create a uihtml component
htmlComponent = uihtml(fig);
htmlComponent.Position = [20 20 450 130];
htmlComponent.HTMLSource = fullfile(pwd, 'html.html');
% Define the data changed callback function
htmlComponent.DataChangedFcn = @(src, event) dataChangedCallback(src, event);
function dataChangedCallback(~, event)
% Extract the data sent from HTML
data = event.Data;
if isfield(data, 'Name')
disp(['Name: ', data.Name]); % Display the name in the command window
end
end
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function setup(htmlComponent) {
document.getElementById('myForm').addEventListener('submit', function (event) {
event.preventDefault(); // Prevent the default form submission
// Get the input value
var name = document.getElementById('inputName').value;
// Send data to MATLAB
htmlComponent.Data = {Name: name};
// Display the data within the HTML
document.getElementById("dataDisplay").innerHTML = 'Name: ' + name;
});
}
</script>
</head>
<body>
<form id="myForm">
<label for="Name">Input your name:</label>
<input type="text" id="inputName">
<button type="submit" id="submit">Submit</button>
<br>
<div id="dataDisplay">
Display data here..
</div>
</form>
</body>
</html>
Hope this helps!