How to get array value in seperate combobox - javascript

I want to get the array value in separate comboboxes using JavaScript and PHP. Suppose i have array like
0:{"id":"none","name":"none"},1:{"id":"none","name":"none"},2:{"id":"write","name":"write"}
I want that 0 index array will show in first combo box, 1 index array will show in 2nd combo box and so on, all combo boxes having same name. But when I done it is showing all arrays in one combo box .Here is my code
var data = [{
"id": "none",
"name": "none"
}, {
"id": "none",
"name": "none"
}, {
"id": "write",
"name": "write"
}]
$.each(data, function(i, item) {
$('#modules').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="modules"></select>

You want 3 dropdowns?
var data = {
"one": [{ "id": "none", "name": "none 1" }, { "id": "none", "name": "none 1" }, { "id": "write", "name": "write 1" }],
"two": [{ "id": "none", "name": "none 2" }, { "id": "none", "name": "none 2" }, { "id": "write", "name": "write 2" }],
"three": [{ "id": "none", "name": "none 3" }, { "id": "none", "name": "none 3" }, { "id": "write", "name": "write 3" }]
}
$.each(data, function(i, item) {
var $sel = $("<select/>", {
"name": "data"
});
$.each(item, function(i, selItem) {
$sel.append('<option value="' + selItem.id + '">' + selItem.name + '</option>')
});
$('#modules').append($sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modules"></div>

If you wanted to achieve this using plain JavaScript, please see below snippet with desired output - select dropdown with text from objects in array populating the options.
var data = [{
"id": "none",
"name": "none"
}, {
"id": "none",
"name": "none"
}, {
"id": "write",
"name": "write"
}]
function comboBox(data) {
const select = document.getElementById('modules')
data.map(object => {
let option = document.createElement("option");
option.value = object.id;
option.text = object.id;
select.appendChild(option);
})
}
comboBox(data);
<select id="modules"></select>

i think you want to show data in dropdown
just make sure your array is in correct format.
var data = [{"id":"none","name":"none"},
{"id":"none","name":"none"},
{"id":"write","name":"write"}];
$.each(data,function(i,item){
$('#modules').append('<option value="'+data[i].id+'">'+data[i].name+'</option>'); });
$('.modules').eq(i).append('<option value="' + data[i].id + '">' + data[i].name + '</option>');

Related

How to show localstorage data in HTML form using jquery or javascript?

I am saving data in localstorage temporary, because of user have to go to another page before submit the form, But i have problem to display data in form again.
Here is my code
$('#ip_range').click(function(e) {
var data = $('#Demoform').serializeArray();
// localStorage.setItem('formData', JSON.stringify(data));
var formData = JSON.parse(localStorage.getItem('formData'));
$.each(formData, function(i, val) {
var data = $("input[name='"+val.name+"']").val(val.value);
console.log(data);
});
});
This is the json data that i want to display
[{
"name": "timezone",
"value": "America/New_York"
}, {
"name": "fiscal_year",
"value": "1"
}, {
"name": "first_day",
"value": "0"
}, {
"name": "highest_level",
"value": "393"
}, {
"name": "company_administrator",
"value": "393"
}, {
"name": "ip_restrictions",
"value": "1"
}, {
"name": "ip_range",
"value": "4"
}, {
"name": "languages_enabled",
"value": "0"
}, {
"name": "language",
"value": ""
}, {
"name": "enable_single_sign",
"value": "0"
}, {
"name": "user_sign_off",
"value": "0"
}, {
"name": "widgets_sort_order",
"value": "Links,Training,Task"
}, {
"name": "confirm",
"value": "1"
}]
You are close here, but this part $("input[name='"+val.name+"']").val(val.value) is what I think your problem is. Try the code below. I think this is what you are trying to do.
I would structure the input like such: var data = $('<input name="'+ val.name +'" value="'+ val.value +'" />');
I'd put a stack snippet up, but it doesn't work well with localStorage, so click on the jsfiddle link and click the IP Range button to see the form get the inputs with the proper names.
Demo: https://jsfiddle.net/ygh8pdk1/
var data = [
{
"name": "timezone",
"value": "America/New_York"
}, {
"name": "fiscal_year",
"value": "1"
}, {
"name": "first_day",
"value": "0"
}, {
"name": "highest_level",
"value": "393"
}, {
"name": "company_administrator",
"value": "393"
}, {
"name": "ip_restrictions",
"value": "1"
}, {
"name": "ip_range",
"value": "4"
}, {
"name": "languages_enabled",
"value": "0"
}, {
"name": "language",
"value": ""
}, {
"name": "enable_single_sign",
"value": "0"
}, {
"name": "user_sign_off",
"value": "0"
}, {
"name": "widgets_sort_order",
"value": "Links,Training,Task"
}, {
"name": "confirm",
"value": "1"
}
];
localStorage.setItem('formData', JSON.stringify(data));
$('#ip_range').click(function(e) {
var formData = JSON.parse(localStorage.getItem('formData'));
$.each(formData, function(i, val) {
var data = $('<input name="'+ val.name + '" value="'+ val.value +'" />');
$('#form-data').append(data);
});
});

Jquery multiply input number value and Json data

I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/

Get value from specific JSON object based on first selection

I have a set of dropdowns which I will be populating with JSON. What I would like to do is populate the first dropdown with the name of each object. Then when someone selects an option from the first dropdown, the second dropdown is populated with other data pertaining to their first selection. What I have right now is populating the first select box with the name of a product and assigning the value to the ID For the second dropdown I want the options to be based on the options associated with the product that was selected in the first dropdown, based on ID.
Here's what I have so far, I am not sure how to only get the data from the selected product based on the products ID:
$(function() {
var products = [{
"id": 0,
"name": "First Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
},
{
"id": 1,
"name": "Second Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
}
]
$.each(products, function(key, val) {
$('.first').append('<option value="' + val.id + '">' + val.name + '</option>');
});
$('.first').change(function() {
var selectedProduct = $(this).val();
$.each(products['id'][selectedProduct], function(key, val) {
$('second').append('<option id="' + val.sizes.size + '">' + val.sizes.size + '</option>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="first">
</select>
<select class="second">
</select>
$(function() {
var products = [{
"id": 0,
"name": "First Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
}, {
"id": 1,
"name": "Second Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
}]
$.each(products, function(key, val) {
$('.first').append('<option value="' + val.id + '">' + val.name + '</option>');
});
$('.first').change(function() {
var selectedProduct = $(this).val();
var getProduct = products.filter(function( obj ) {
return obj.id == selectedProduct;
});
$('.second').find('option').remove();
$.each(getProduct[0].sizes, function(key, val) {
$('.second').append('<option id="' + val.size + '">' + val.size + '</option>');
});
});
});
You just need to iterate over products again to find the one with the currently selected ID. Then, iterate over its sizes and fill the second just like you did with the first.
Clear the options each time.
And, trigger a 'change' at the start to get the second's filled to begin with.
$(function() {
var products = [{
"id": 0,
"name": "First Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
},
{
"id": 1,
"name": "Second Product",
"sizes": [{
"size": "med"
},{
"size": "large"
}]
}
]
$.each(products, function(key, val) {
$('.first').append('<option value="' + val.id + '">' + val.name + '</option>');
});
$('.first').change(function() {
var selectedProduct = $(this).val();
$.each(products, function(key, val) {
if (val.id==selectedProduct) {
$('.second').find('option').remove();
$.each(val.sizes, function(key2, val2) {
$('.second').append('<option value="' + val2.size + '">' + val2.size + '</option>');
});
}
});
});
$('.first').trigger('change');
});
You could stick the object on the option as a data field for reference.
$(function() {
var products = [{
"id": 0,
"name": "First Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
},
{
"id": 1,
"name": "Second Product",
"sizes": [{
"size": "small"
},{
"size": "medium"
}]
}
]
$.each(products, function(key, val) {
var $option = $('<option>').val(val.id).text(val.name).data('object-reference', val);
$('.first').append($option);
});
$('.first').change(function() {
var selectedProduct = $(this).find('option:selected');
$.each(selectedProduct.data('object-reference').sizes, function(key, val) {
$('.second').append('<option id="' + val.size + '">' + val.size + '</option>');
});
});
setTimeout(function(){
products[1].sizes = [ { 'size': 'changed1' }, { 'size': 'changed2' } ];
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="first">
</select>
<select class="second">
</select>

jQuery JSON append ul according to the number of array sets

I want jQuery to make new ul for each set of products.
Inside of each ul, all items of each set will be appended.
The result was unexpected; there should be only 2 ul, but
11 ul were appended.
My jQuery
$.getJSON('/products.json', function (result) {
var booksobj = result.ebooks.basic;
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
});
});
products.json
{
"ebooks": {
"basic": {
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
],
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
]
}
}
}
Thanks in advance.
You're looping over set and for each item inside a set, you're creating a new ul element. You need to have multiple loops where you create an ul and afterwards add all the lis for the section. I changed your data structure, you don't need the set properties (and they're overriding each other as property names are unique). basic is now an array which consists of arrays which represent a set.
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
data.ebooks.basic.forEach(function(set) {
var $list = $('<ul></ul>');
set.forEach(function(pdf) {
$list.append('<li>' + pdf.title + '</li>')
});
$('#ebook').append($list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ebook"></div>
It looks like the problem stems from the selectors in this snippet:
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
The selector "$('#ebook ul')" won't select the newly added ul in the iteration, instead it'll append to the first match (so the first ul added to the #ebook div). Instead, try chaining your calls like so:
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>').append('<li>' + item.title + '</li>');
});
Working example with JSON data in a variable: http://codepen.io/JasonGraham/pen/WxbvRo
Your problem is use $('#ebook ul'), another question, why you use the key "set" two times? No make sense,
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
$.each(data.ebooks.basic, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$.each(item, function(i, item2) {
$('#ebook ul:last').append('<li>' + item2.title + '</li>');
});
});
see the fiddle

Iterate JsonObject

Hi this is my JsonObject i want to iterate this and get the values of title elements class of header , Container and footer.
var jsonObj = [{
"Header": {
"title": "Header",
"element":"div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Container": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Footer": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable": "true"
}
}]
You can do this by
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " -> " + jsonObj[0][key].title);
}
}
Here id the fiddle for this code.
For getting the inner elements from the object we have to extend the previous loop
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " ---");
for(innerKey in jsonObj[0][key]) {
console.log(innerKey + " -> " + jsonObj[0][key][innerKey])
}
console.log("-----")
}
}
Here is the fiddle for above code

Categories

Resources