Iterate through JSON object array radio button - javascript

A JSON like this is with me in a variable
var options_array =
[{"optionText":"1safsafs 1","optionDbId":1},{"optionText":"1safsafs 2","optionDbId":2},{"optionText":"1safsafs 3","optionDbId":3},{"optionText":" 1safsafs 4","optionDbId":4}]
I have to build a radio buttons with the items in this JSON and i am using the below code
var choice_div = document.getElementById("choice_div");
var options_array = "[{\"optionText\":\"1safsafs 1\",\"optionDbId\":1},{\"optionText\":\"1safsafs 2\",\"optionDbId\":2},{\"optionText\":\"1safsafs 3\",\"optionDbId\":3},{\"optionText\":\" 1safsafs 4\",\"optionDbId\":4}]";
console.log(options_array);
console.log(options_array.length); //174 is coming here instead of 4
for (i = 0; i < options_array.length; i++) {
var _text = JSON.stringify(options_array[i].optionText);
//console.log(_text); //all values are coming as undefined
var _value = JSON.stringify(options_array[i].optionDbId);
//console.log(_value);
var option_entry = makeRadioButton("selectedoption", _value, _text);
choice_div.appendChild(option_entry);
}
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
but this code is adding 170 items to the DIV and i am getting radio button contents as undefined . Not able to spot the reason?
I am expecting this to build 4 radio buttons with 4 options in it

you had some funny errors XD, first this the working one
$(document).ready(function () {
var choice_div = document.getElementById('mydiv');
data = [{ "optionText": "1safsafs 1", "optionDbId": 1 }, { "optionText": "1safsafs 2", "optionDbId": 2 }, { "optionText": "1safsafs 3", "optionDbId": 3 }, { "optionText": " 1safsafs 4", "optionDbId": 4 }]
$.each(data, function (key, item) {
var text = item.optionText;
var value = item.optionDbId;
console.log(value);
var option_entry = makeRadioButton("option" + key, value, text);
choice_div.appendChild(option_entry);
});
});
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
console.log("bot "+value);
label.appendChild(document.createTextNode(text));
return label;
}
then lets check what you did first you used JSON.stringify() with no reason , secondly you typed the json keys wrong thats was a little funny XD.

Javascript Object key is case sensitive. You've made some typos on your object keys.
optiontext -> optionText
optiondbid -> optionDbId
for (i = 0; i < options_array.length; i++) {
var _text = JSON.stringify(options_array[i].optionText);
//console.log(_text);
var _value = JSON.stringify(options_array[i].optionDbId);
//console.log(_value);
var option_entry = makeRadioButton("option" + i,_value, _text);
choice_div.appendChild(option_entry);
}
Update (11/10/2019)
The reason you are getting incorrect length is because you are logging JSON string length ( number of characters in your JSON string ) instead of the array length.
var choice_div = document.getElementById("choice_div");
// Get options_array as actual array instead of JSON string
var options_array = JSON.parse("[{\"optionText\":\"1safsafs 1\",\"optionDbId\":1},{\"optionText\":\"1safsafs 2\",\"optionDbId\":2},{\"optionText\":\"1safsafs 3\",\"optionDbId\":3},{\"optionText\":\" 1safsafs 4\",\"optionDbId\":4}]");
for (i = 0; i < options_array.length; i++) {
// Dont need to stringify here
var _text = options_array[i].optionText;
var _value = options_array[i].optionDbId;
var option_entry = makeRadioButton("selectedoption", _value, _text);
choice_div.appendChild(option_entry);
}
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}

Related

How do i add a new element in a list element with javascript?

I like to add an input field to my list element for the timer im working on.
The problem is that it can read the function but doesnt display the object.
//Input Element Object
function inputElement() {
this.input = document.createElement("input");
this.input.id = "Timer " + count
this.input.type = "number";
this.input.max = 10;
this.input.min = 01;
}
function LI(id) {
this.li = document.createElement("li");
this.li.id = id;
this.li.id += count;
this.input = new inputElement();
this.li.innerHTML += this.input + ` set Timer`;
this.setting = document.getElementById("Version3");
this.setting.append(this.li);
}

How can I use local variable from one function and use them in another function, if this is even possible?

My Problem
I have a function called mathsFormula() which is supposed to calculate the two input fields located in the second function called renderRow() and display that answer in the <div> labelled result.
However, I don't know how to attach the local variables from renderRow() function so they work inside the mathsFormula().
What is the best solution to solve this problem?
This is the mathsFormula() function
document.addEventListener("keyup", mathsFormula());
function mathsFormula() {
const calculate = (input1.value * input2.value) - input2.value;
result.textContent = calculate
}
This is the renderRow() function
function renderRow() {
const row = document.createElement('div');
const label = document.createElement("label");
const input1 = document.createElement("input");
input1.type = "number";
const input2 = document.createElement("input");
input2.type = "number";
const result = document.createElement("div");
row.append(label, input1, input2, result);
You need to expose these variables by returning them from the function. You can return them in an object, e.g. return { bet_label, input_field, input_div };, so when the function is called it will return an object containing references to these elements.
function addRow(rowNumber) {
const bet_label = document.createElement("label");
a.appendChild(bet_label);
bet_label.classList.add('betLabel');
bet_label.textContent = "Bet " + rowNumber;
const input_field = document.createElement("input");
a.appendChild(input_field);
input_field.classList.add('oddsEntry');
input_field.type = "number";
const input_div = document.createElement("input");
a.appendChild(input_div);
input_div.classList.add('stakeEntry');
input_div.type = "number";
const result_div = document.createElement("div");
a.appendChild(result_div)
result_div.classList.add('resultDiv');
result_div.textContent = "";
const btn_Del = document.createElement("button");
btn_Del.classList.add('deleteBtn');
btn_Del.innerHTML = '<i class="fa-solid fa-trash"></i>';
a.appendChild(btn_Del);
return {
bet_label,
input_field,
input_div,
result_div,
btn_Del
};
}

Javascript - cannot dynamically create checked checkboxes

I have the following function that dynamically creates a bunch of checkboxes:
var drawGroups = function(){
var groups = document.getElementById("groups"); //groups element is a div
groups.innerHTML = "";
//groupList is an array containing strings
for(var i in groupList){
var groupName = groupList[i];
var cb = document.createElement('input');
cb.type = "checkbox";
cb.checked = true; //this seems to do nothing
groups.appendChild(cb);
groups.innerHTML += groupName + "<br/>"
}
}
Everything I read indicates cb.checked = true should check the checkbox, but it doesn't seem to do anything. How can I create the checkboxes in a checked state?
You need to set the defaultChecked property:
var groupList = ['foo','bar','baz','biz','boz'];
var drawGroups = function(){
var groups = document.getElementById("groups"); //groups element is a div
groups.innerHTML = "";
//groupList is an array containing strings
for(var i in groupList){
var groupName = groupList[i];
var cb = document.createElement('input');
cb.type = "checkbox";
cb.defaultChecked = true;
groups.appendChild(cb);
groups.innerHTML += groupName + "<br/>"
}
}
drawGroups();
<div id="groups"></div>
You could use the method setAttribute:
cb.setAttribute('checked', true);

Javascript - Pass param function to async onchange event

Good evening,
I have a problem with the construction of form in Javascript. For avoid the repetition of code I'd like to use the same function:
function addCheckBoxItem(p, name, value) {
// add checkbox
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.setAttribute("value", p);
newCheckbox.setAttribute("id", p);
newCheckbox.setAttribute("name", name);
newCheckbox.onchange = function(){
var cbs = document.getElementsByName(name);
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
this.checked = true;
// define the peer selected as choice
value = this.value;
// TODO: MY PROBLEM IS HERE
};
form.appendChild(newCheckbox);
// add label to checkbox
var label = document.createElement('label');
label.setAttribute("name", name);
label.htmlFor = p;
label.appendChild(document.createTextNode(p));
form.appendChild(label);
// add br tag to checkbox
var br = document.createElement("br")
br.setAttribute("name", name);
form.appendChild(br);
}
I call my function inside loop
for (i = 0; i < array.length; i++) {
addCheckBoxItem(array[i].key, nameItemCheckbox, peer_choice);
}
I know that value = this.value isn't possible because onchange event is Async but i want retrieve the value of this event and associate it with my param. I have find different response to this problem. One of this is: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference I have understand the basic concept but none of the example is relevant to my problem. Someone could help me?
EDIT - SOLUTION
Thanks to #Tibrogargan i have modified my function in this way:
for (i = 0; i < array.length; i++) {
addCheckBoxItem(form, array[i].key, form_peer_available_class, peer_choice, (value) => peer_choice = value);
}
and
function addCheckBoxItem(p, name, value, callback) {
// add checkbox
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.setAttribute("value", p);
newCheckbox.setAttribute("id", p);
newCheckbox.setAttribute("name", name);
newCheckbox.onchange = function(){
var cbs = document.getElementsByName(name);
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
this.checked = true;
// define the peer selected as choice
callback(this.value);
};
form.appendChild(newCheckbox);
// add label to checkbox
var label = document.createElement('label');
label.setAttribute("name", name);
label.htmlFor = p;
label.appendChild(document.createTextNode(p));
form.appendChild(label);
// add br tag to checkbox
var br = document.createElement("br")
br.setAttribute("name", name);
form.appendChild(br);
}
Pass callback into addCheckBoxItem like that
// accumulator
var data = {}
// callback
var storeData = (name, value, p) => data[name] = value;
// callback as third argument
addCheckBoxItem('data1', 'checkbox1', storeData);
addCheckBoxItem('data2', 'checkbox2', storeData);
addCheckBoxItem('data3', 'checkbox3', storeData);
Check full example here http://jsfiddle.net/gtqnc109/9/

Split values by comma separated string in javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>

Categories