Let’s say I have form like this.
<html>
<body>
<form>
<div>
<input id="brand" name="brand" type="text" value="toyota">
</div>
<div>
<input id="color" name="color" type="text" value="blue">
</div>
<div>
<input id="json_field" name="json_field" type="text" value='{"brand": "toyota", "color": "blue"}' size= 50 readonly>
</div>
</form>
</body>
</html>
What I want is:
- when I change ‘brand’ field to ‘nisan’, the json_field auto change
{"brand": "nisan", "color": "blue"}
- when I change ‘color’ field to ‘red’, the json_field auto change
{"brand": "nisan", "color": "red"}
Kindly please tell me how to do it.
3
Answers
Good question – updating a field based on the value from another field is a super common use case and there are six quintillion ways to do it. So here’s one way.
First, set up an event listener on your brand field (you’ll do the same for your color field, too). Notice the
onChange
property – this will call the functiononBrandFieldChange
any time the user updates the value in the brand field.Then, create the event listener that updates the JSON field value.
If you use jQuery, a Framework for JavaScript, it can be a bit easier to make the jump from Python.
Consider the following example.
Add
onchange="updateJsonField()"
ininput
tag then add functionupdateJsonField()
in script tag of html file or js file,json_field
auto change when change brand or color