How to display object values on a webpage - html

I am trying to get user's input from multiple fields.
So here's my javascript to get the value from the html contents::
var myButton = document.getElementById('button');
var inp = document.getElementById('myInput');
var inpw = document.getElementById('myPW');
And here where I would like to display the inputs:
<h2>Data</h2>
<p id="val"></p>
What I've done is:
myButton.addEventListener('click', function(event) {
event.preventDefault();
const object1 = {
un: inp,
pw: inpw
};
document.getElementById('val').innerHTML = Object.values(object1);
});
But the result is:
[object HTMLInputElement],[object HTMLInputElement]

I already figure it out:
const object1 = {
un: inp.value,
pw: inpw.value
};
var myJSON = JSON.stringify(object1);
document.getElementById('val').innerHTML = myJSON;
Output:
{"un":"erin","pw":"pdds"}

Related

How to properly use html-to-react?

so i am learning about this package html-to-react, and for the most part, i understand it. However, their is a piece of code i just cannot seem to be able to get my head around. The code is:
var React = require('react');
var HtmlToReact = require('html-to-react');
var HtmlToReactParser = require('html-to-react').Parser;
var htmlToReactParser = new HtmlToReactParser();
var htmlInput = '<div><div data-test="foo"><p>Text</p><p>Text</p></div></div>';
var htmlExpected = '<div><div data-test="foo"><h1>Heading</h1></div></div>';
var isValidNode = function () {
return true;
};
var processNodeDefinitions = new HtmlToReact.ProcessNodeDefinitions(React);
// Order matters. Instructions are processed in
// the order they're defined
var processingInstructions = [
{
// This is REQUIRED, it tells the parser
// that we want to insert our React
// component as a child
replaceChildren: true,
shouldProcessNode: function (node) {
return node.attribs && node.attribs['data-test'] === 'foo';
},
processNode: function (node, children, index) {
return React.createElement('h1', {key: index,}, 'Heading');
}
},
{
// Anything else
shouldProcessNode: function (node) {
return true;
},
processNode: processNodeDefinitions.processDefaultNode,
},
];
var reactComponent = htmlToReactParser.parseWithInstructions(
htmlInput, isValidNode, processingInstructions);
var reactHtml = ReactDOMServer.renderToStaticMarkup(
reactComponent);
assert.equal(reactHtml, htmlExpected);
The code i don't understand is the:
shouldProcessNode: function (node) {
return node.attribs && node.attribs['data-test'] === 'foo';
},
Any help would be very appreciated. Thanks

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

Unable to store and retrieve JSON value by JQUERY

I have two textbox(goalText and goalText1) and a button(goalreach) in my html.
My aim : When I enter numeric value in 1 textbox(goalText), it should be converted to json and be stored. So even after 5 days when I run the application, it should be stored. Now when I enter the numeric value, in other textbox(goalText1) and it matches, I am simply displaying the message match. This is the demo, I am trying so that I can know that value can be stored in json and can be retrieved when necessary. I have written the code as follow:
$("#goalreach").click(function () {
var contact = new Object();
contact.goalDist = "$("#goalText.value ").val()";
var jsonText = JSON.stringify(contact);
if (jsonText == ($("#goalText1.value").val())) {
document.getElementById('divid').innerHTML = 'Match';
}
});
I know, I have made many simple mistakes of brackets and " too, but I am a newbie, If you can help me out.
First, you have to compare either 2 objects or 2 strings, and in goalDist, you should store the value (BTW, you get the jQuery object with $("#goalText") and the value with somejQueryObject.val() moreover this is generally equivalent to document.getElementById("goalText").value)...
This can be done like this :
$("#goalreach").click(function () {
// Create an object with the single property "goalDist"
var contact = { goalDist : $("#goalText").val() };
// Makes it be a string (it will in this simple example : `"{"goalDist":<the value of goalTest>}"`
var jsonText = JSON.stringify(contact);
// Creates a string from an equivalent object bound on the second field
var jsonText2 = JSON.stringify({ goalDist : $("#goalText2").val() });
// Compares the 2 strings
if (jsonText === jsonText2) {
document.getElementById('divid').innerHTML = 'Match';
}
});
TRY THIS
$("#goalreach").click(function () {
var contact = new Object();
var goalDist = '$("#goalText.value").val()';
var jsonText = JSON.stringify(contact.goalDist);
if(jsonText==($("#goalText1.value").val()))
{
document.getElementById('divid').innerHTML = 'Match';
}
});
Try the following code:
$("#goalreach").click(function () {
var contact = new Object();
contact.goalDist = $("#goalText").val();
var jsonText = JSON.stringify(contact);
if (jsonText == ($("#goalText1").val())) {
document.getElementById('divid').innerHTML = 'Match';
}
});
OR
$("#goalreach").click(function () {
var goalText = $("#goalText").val();
var goalText1 = $("#goalText1").val();
if (goalText == goalText1) {
document.getElementById('divid').innerHTML = 'Match';
}
});

Read list from json object

I am try to read list from json here id my code:-
List<EmailProvider> list = new List<EmailProvider>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WidgetXml.xml"));
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//widget");
foreach (XmlNode node in nodes)
{
EmailProvider obj = new EmailProvider();
obj.Name = node["Name"].InnerText;
obj.left = Convert.ToInt32(node["left"].InnerText);
obj.Id = node["id"].InnerText;
obj.IsVisible = Convert.ToBoolean(node["isActive"].InnerText);
long s = Int64.Parse(node["top"].InnerText);
obj.top = s;
obj.desc = node["desc"].InnerText;
list.Add(obj);
}
var result = list.OrderBy(p => p.IsVisible).ToList();
return result.ToArray();
and on view:-
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
alert(data.length);
var st = JSON.stringify(data);
alert(st.length);
});
});
length always show 54 but in array only 4 items. How can i read all recors from array by json from json object.
Thanks in advance.
Try returning a JsonResult from your controller method, using the controller method Json
var result = list.OrderBy(p => p.IsVisible).ToList();
return Json(result.ToArray());
On JavaScript, you should just need to iterate over the array as in:
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
for(var i = 0;i < data.length; i++){
alert(data[i].Name);
}
});
});