update a json field when another field is changed in html javascript? - javascript

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.

If you use jQuery, a Framework for JavaScript, it can be a bit easier to make the jump from Python.
Consider the following example.
$(function() {
// Define an Object use by other functions
var myJson = {
brand: "",
color: ""
};
// Define a Function to update the Object and output it to a Text Field
function updateJson(key, value) {
myJson[key] = value;
$("#json_field").val(JSON.stringify(myJson));
}
// Bind the "change" event to an HTML Element and perform a specific anonymous function
$("input").change(function() {
updateJson($(this).attr("id"), $(this).val());
// this is reference to the element that is the subject of the event
// $(this) is a jQuery Object of the Element
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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=5 0 readonly>
</div>
</form>

Add onchange="updateJsonField()" in input tag then add function updateJsonField() in script tag of html file or js file,
json_field auto change when change brand or color
<html>
<body>
<form>
<div>
<input id="brand" name="brand" type="text" value="toyota" onchange="updateJsonField()" />
</div>
<div>
<input id="color" name="color" type="text" value="blue" onchange="updateJsonField()" />
</div>
<div>
<input id="json_field" name="json_field" type="text" value='{"brand": "toyota", "color": "blue"}' size="50" readonly />
</div>
</form>
</body>
<script>
function updateJsonField() {
var brand = document.getElementById("brand").value;
var color = document.getElementById("color").value;
document.getElementById("json_field").value = JSON.stringify({ brand: brand, color: color });
}
</script>
</html>

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 function onBrandFieldChange any time the user updates the value in the brand field.
<input id="brand" name="brand" type="text" value="toyota" onChange="onBrandFieldChange">
Then, create the event listener that updates the JSON field value.
// First, store a reference to the JSON field so you can manipulate its value
const jsonField = document.querySelector("#json_field");
function onBrandFieldChange(event) {
// newBrand will be "nissan" or "toyota" or something else
const newBrand = event.target.value;
// Read the jsonField value (which comes in as a string)
// Parse it into an actual JavaScript object
const jsonFieldValue = JSON.parse(jsonField.value);
// Update the "brand" property in your jsonField
jsonFieldValue["brand"] = newBrand;
// Reset the field value (converting it back to a string)
jsonField.value = JSON.stringify(jsonFieldValue);
}

Related

How do I use DOM element's attribute value as a variable?

Got a number of dynamic values assigned to variables from outside the form. And I need to pass them to form. Now, I could do each field individually like this.
this would be the form
<form>
<input type="text" class="inputfield widthfield" id="widthval" />
<input type="text" class="inputfield fontsizefield" id="fontsize" />
</form>
And this would be jquery
widthval = '300px'
fontsize = '15px'
$(".widthfield").val(widthval);
$(".fontsizefield").val(fontsize);
and so on. But there is a ton of these fields, and this doesn't look right. So, I was wondering if there is any way to use field id to match field and variable.
Something like this perhaps (the logic).
$(".inputfield").each(function(){
matchattr = $(this).attr("id");
$(this).val(matchattr);
});
In this case, it uses the actual value of an attribute. How do I turn that value into variable that has the dynamic value assigned to it?
Thanks!
Given that your variables match the ids of the inputs, you could put your values in an object, loop over the keys, and set them when they match.
var data = {
widthval: '300px',
fontsize: '15px'
};
var $inputfields = $('.inputfield');
Object.keys(data).forEach(function(key){
$inputfields.filter('#'+ key).val(data[key]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" class="inputfield widthfield" id="widthval" />
<input type="text" class="inputfield fontsizefield" id="fontsize" />
</form>

Riot.js: Toggle class on label if input has value

I need to toggle class .has-data on label if input has some data
<label>
<input type="text">
</label>
Can it be done just using some markup without writing javascript?
No, you'll have to write some JavaScript, but the JavaScript is pretty minimal. Change the HTML to this:
<label class="{ has-data: entry }">
<input type="text" onkeyup="{updateEntry}">
</label>
And add this section to the component's script:
<script>
this.entry = '';
updateEntry(e) {
this.entry = e.target.value;
}
</script>

Create Custom validation Class in javaScript/Jquery

Let say there is an input element field and i want to create a new validation class myClass ,that i can insert with any html element that might performing some function and also setting attribute such as
readonly="true"
required='true'.
HTML is
<td>
<input type="text" id="endDate" name ="endDate" class="select_200" required readonly="true">
</td>
Now rather setting elements separately need one class for performing:
A function check "let say character count less then 10" and setting
attribute.
Setting attributes such as readonly ,required
So that i can add that class to all elements with similar property.
Validation + Setting/ Reseting attributes by adding class only
You can set your own custom attributes for your input elements and use those custom attributes to query the input fields and perform various actions. You can find my sample below.
$(function () {
//Set various input field attributes here
$("input[data-myCustomClass]").each(function(){
//$(this).attr("readonly", true);
$(this).attr("required", true);
});
//Sets max length - you can change this code to retrieve info from attribute
$("input[data-setFieldLength]").each(function(){
$(this).attr("maxlength", 10);
});
//Validate for field length based on "validateFor" attribute
$("input[data-validateFieldLength]").each(function(){
$(this).on('focusout', function(){
var validateFor = $(this).attr("validateFor");
if ($.trim($(this).val()).length < parseInt(validateFor))
{
$(this).focus();
$(this).select();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" data-myCustomClass data-setFieldLength id="field1" />
<input type="text" data-myCustomClasss id="field2" />
<input type="text" data-setFieldLength id="field3" /> <!-- set field length to 10 -->
<input type="text" data-validateFieldLength id="field4" validateFor="5" /> <!-- validate for 5 characters and return focus -->
you have create new function for a field?
on
<form onsubmit="return validate()" name="form">
<td>
<input type="text" id="custname" name ="endDate" class="select_200"
required readonly="true">
<font style="color:red" id="custnameerror"></font>
</td>
<button onclick="return validate()"></button>
</form>
javascript validation function like
<script type="text/javascript">
function validate(from)
{
var error=document.getElementById("custnameerror");
var custname=form["custname"].value;
error.innerHTML="";
if( custname==null || custname==""){
error.innerHTML="Enter customer name";
return false;
}
if(custname.length<3){
error.innerHTML="Customer name should be minimum 3 character";
return false;
}
if(custname.length>80){
error.innerHTML="Customer name should be in between 3 to 80
character";
return false;
}/*end */
</script>

Toggle field depending on value

$(document).ready(function () {
toggleFields();
});
function toggleFields() {
if ($("#people").val() == 1)
$("#personen1").show();
else
$("#personen1").hide();
$("#personen2").hide();
$("#personen3").hide();
$("#personen4").hide();
$("#personen5").hide();
$("#personen6").hide();
$("#personen7").hide();
$("#personen8").hide();
}
<p>Personen:
<input type="number" id="people" name="ppl" min="1" class="uniform-input number" value="1" required="">
</p>
<div id="personen1">
<p>1. Person:
<input id="personen1_person1" type="text" name="person_name" />
</p>
</div>
<div id="personen2">
<p>1. Person:
<input id="personen2_person1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="personen2_person2" type="text" name="person2_name" />
</p>
</div>
<div id="personen3">
<p>1. Person:
<input id="personen3_person1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="personen3_person2" type="text" name="person2_name" />
</p>
<p>3. Person:
<input id="personen3_person3" type="text" name="person3_name" />
</p>
</div>
I have a people number input on my landingpage. I want to use the input value to add fields to my checkout. Like if the input is 5 I want 5 fields in my checkout page so the customer can fill in the names. The code above is not working correctly. What am I missing?
The first and foremost mistake you are making is duplicating ids, which are supposed to be unique, else unintended effects may appear.
The next thing is, the snippet will not work because you haven't included jQuery library, which is more important than anything to execute the $ function.
Thirdly, find these mistakes you have made:
You didn't bind the event with the input.
You need to check the input for the existence of id.
You aren't closing the if correctly.
You can compress the code a lot of effective ways, by using class or by using ids in a single $ selector.
$(document).ready(function () {
toggleFields();
$("#people").on("keyup change", function () {
toggleFields();
});
});
function toggleFields() {
$("#personen1, #personen2, #personen3, #personen4, #personen5, #personen6, #personen7, #personen8").hide();
if ($("#people").val() < 9)
$("#personen" + $("#people").val()).show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Personen:
<input type="number" id="people" name="ppl" min="1" class="uniform-input number" value="1" required="">
</p>
<div id="personen1">
<p>1. Person:
<input id="person1-1" type="text" name="person_name" />
</p>
</div>
<div id="personen2">
<p>1. Person:
<input id="person2-1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="person2-2" type="text" name="person2_name" />
</p>
</div>
<div id="personen3">
<p>1. Person:
<input id="person3-1" type="text" name="person_name" />
</p>
<p>2. Person:
<input id="person3-2" type="text" name="person2_name" />
</p>
<p>3. Person:
<input id="person3-3" type="text" name="person3_name" />
</p>
</div>
You should not have multiple ids with same value.
That is not a right way of doing this, you should generate the HTML using JavaScript only:
// Sample code, you can create a function for this as well.
$(function(){
var count = 5; // Change this count with the input field value.
var _html = "";
for(var i=0; i<count; i++){
_html += '<p>'+(i+1)+'. Person:'
+'<input id="person'+(i+1)+'" type="text" name="person'+(i+1)+'_name" />'
+'</p>';
}
$(".container").html(_html);
});
Here is a fiddle
Every id attribute you use on a webpage has to be unique in the entire document, also -- you're using some kind of template to load when a user types a number but what if a user wants to add 10 people instead of 3 or 5? Individually adding cases will cause you much pain in the future.
I also understand that you want users to input a number and then get a certain amount of fields back from that, with that assumption made the code
$(document).ready(function() {
toggleFields();
});
will not work since it only gets executed once, onload of the page and doesn't get executed anymore after that since no events are bound.
var insertPeople = function(n) {
var amt = !isNaN(n) ? n : 1;
var fieldStr = '';
//using a for loop to 'build' the fields dynamically
for (var i = 0; i < amt; i++) {
var num = i + 1;
fieldStr += '<p>'+ num +'. person<input type="text" id="person'+ num +'" name="person'+ num +'_name"></p>'
}
//append HTML to container
$('#people-container').html(fieldStr);
}
//Use this to insert fields on page load instantly.
$(insertPeople);
//Use this if you would like a user to control the amount of fields through an input field.
$(function() { //shorthand for $(document).ready
$('#people').on('keyup', function() {
insertPeople($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="people" value="1" />
<div id="people-container"></div>
This code will loop for n times where n is the user input (validate the type of that yourself) and creates fields with ID's starting from 0 through the end point at the end of the loop. At the last step it appends the fields to a container, if this were a form then that form would simply be submit with those values.

user input to change a variable in a script

I'm using a widget on a web page but learning to code
this is the code i insert into my page:
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
</div>
one of the variables "data-room" i wish to change the value by way of user input. what script/code do i need in order to ask the user for the input and then replace the default value "meetingroom1"
Thanks
Let us say you have an input
<input id="myInput" type="text"/>
Add JS like following
$("#myInput").blur(function(){
$(".bistri-conference").data("room", $(this).val());
});
One approach, using plain JavaScript in this case, is as follows; first showing the HTML:
<!-- wrapping the <inputs> used to update the data in a <form> -->
<form action="#" method="post">
<!-- using <label> elements to allow clicking the text to
focus the relevant <input> -->
<label>Change the meeting room venue:
<!-- using a custom data-* attribute to
clearly denote the data to be
updated by the <input> element's value -->
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<!-- a <button> to trigger the updates: -->
<button type="button" id="update">Update</button>
</form>
<!-- your own posted element, unchanged -->
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12" data-chat="True"></div>
And the JavaScript:
function updateData() {
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
toUpdate = document.querySelector('.bistri-conference');
inputArray.forEach(function (input) {
if (input.value !== input.defaultValue) {
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
document.getElementById('update').addEventListener('click', updateData);
// a named function:
function updateData() {
// Using Function.prototype.call() to use
// Array.prototype.slice() to convert the NodeList
// returned by 'querySelectorAll()' to be converted
// into an Array:
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
// retrieving the element to be updated by this function:
toUpdate = document.querySelector('.bistri-conference');
// iterating over the array of <input> elements, using
// Array.prototype.forEach():
inputArray.forEach(function(input) {
// the 'input' is the current array-element
// from the array over which we're iterating.
// if the value of the <input> is not the
// default-value of the <input>:
if (input.value !== input.defaultValue) {
// we update the data-* attribute of the
// element equivalent to the value held in
// the <input> element's 'data-attribute',
// setting it to the value entered in the <input>:
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
// binding the 'click' event-handler function (note the lack of
// of parentheses after the function's name) of the button:
document.getElementById('update').addEventListener('click', updateData);
label {
display: block;
}
div[data-room]::before {
content: 'current value: ' attr(data-room);
display: block;
}
div[data-room]::after {
content: 'current value: ' attr(data-capacity);
display: block;
}
<form action="#" method="post">
<label>Change the meeting room venue:
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<button type="button" id="update">Update</button>
</form>
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12"
data-chat="True"></div>
JS Fiddle demo.
References:
Array.prototpe.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelector().
document.querySelectorAll().
Function.prototype.call().
HTMLElement.dataset.
HTMLInputElement.
if you are looking something like this ... then try this ;)
<head>
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function Onblur(event) {
var element=document.getElementById("something").value;
$(".bistri-conference").attr("data-room", element);
}
</script>
</head>
<body>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
<input type="text" id="something" onblur="javascript:Onblur(event)" value="Text field" />
</div>
</body>

Categories