How to disable selected field in $('#bootstrap-table') - javascript

Expected Result: If row.updated_status equals to '1', will disable this two field 'UOM' & 'allocated_qty', else remaining.
Issues: Failed to disable the both fields.
"columns": [
{
"field": "id", "title": "Id", "visible": false
},
{
"field": "product__name", "title": "Product"
},
{
"field": "uom", "title": "UOM", "formatter": "uomFormatter"
},
{
"field": "allocated_qty", "title": "Alloc. Qty",
"editable": {"mode": "inline"}
}],
"rowStyle": "rowStyle"
In javascript:
For field 'UOM':
function uomFormatter(value, row, index){
var uom_list = row.uom_list;
var product_id = row.product_id;
if(product_id != null && product_id != ''){
if(row.updated_status == 1){
if(uom_list != null){
var html = '<select class="form-control defaultpicker uom_list" data-row-index="' + index + '" disabled>';
...the following codes...
}else{
...the following codes...
}
}
else{
if(uom_list != null){
var html = '<select class="form-control defaultpicker uom_list" data-width="120px" data-row-index="' + index + '">';
}
}
For Field 'allocated_qty':
function rowStyle(row, index) {
if(row.updated_status == 1){
$('#bootstrap-table').bootstrapTable('disabledColumn', 'allocated_qty');
}
}

It should be disabled, not disable:
var html = '<select class="form-control defaultpicker uom_list" data-row-index="' + index + '" disabled>';

Related

Parse JSON dynamically and print key values on html with input checkbox and get a new JSON of selected keys

I am trying to parse an unknown JSON whose format could be anything. So, I dont know the keys to access it. I want to access every key in JSON and print out all keys and values on screen using HTML. So I made a recursive function to access every key in JSON and used a variable name html to print the keys.
here`s the code:
JSON String:
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209",
"BillAmount": "931.00",
"ConsumerName": "Chetan Kumar Yadav",
"consumerKeysValues": "9352423664",
"partPaymentAllow": "1",
"partPaymentType": "Both",
"lookUpId": "6163298",
"officeCodeValue": "RATNC011"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Mobile Number",
"LableValue": "9352423664"
}, {
"LableName": "Amount After Due Date",
"LableValue": "931.00"
}, {
"LableName": "Bill Date",
"LableValue": "NA"
}, {
"LableName": "Consumer Name",
"LableValue": "Chetan Kumar Yadav"
}, {
"LableName": "Bill Cycle",
"LableValue": "NA"
}, {
"LableName": "Bill Number",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
Heres the code to access every key in Parsed JSON
function scan(info) {
var sub_root = [];
if (info instanceof Object) {
for (k in info) {
if (info.hasOwnProperty(k)) {
console.log('scanning property ' + k);
if (info[k] instanceof Object) {
me += "<div class='root'> <div class='sub_root'> <input class='node' name='sub_root[" + k + "]' value='" + k + "' type='checkbox' />" + k;
console.log(k);
counter++;
scan(info[k]);
me += "</div>";
me += "</div>";
} else {
me += "<div class='json_check' ><input class='node' name='sub_root[" + y + "] [" + k + "]' value='" + k + "' type='checkbox' />" + k + ": " + info[k] + " </div>";
scan(info[k]);
counter++;
}
}
}
} else {
console.log('found value : ' + info);
}
}
After this, I am able to access every key in JSON and printed every node in a nested form with checkboxes in front of them to select any node/key.
Here`s the screenshot:
[PROBLEM to be solved]
Now at the bottom, I have a submit button, when I click on it I want to form a JSON of checked values with their parent nodes. So like if I check a key with a value, I should get its parent keys along with it.
For example: I have selected ServiceName and officeID in TransactionDetails, and some array values in BillDetails, so I should get something like this
{
"FetchDetails": {
"TransactionDetails": {
"ServiceName": "Airtel Mobile Bill Postpaid",
"officeID": "209"
},
"BillDetails": [{
"LableName": "Amount Before Due Date",
"LableValue": "931.00"
}, {
"LableName": "Due Date",
"LableValue": "NA"
}, {
"LableName": "Account Number",
"LableValue": "1116231291"
}]
}
}
[EDITED]
To get this JSON format and traverse through HTML objects I am writing this code:
$('#btn_createservice').on('click', function() {
var solid = '{';
var input = $('input').is(':checked');
if(input){
input = $('input');
}
$('.node:checked').each(function(index) {
var parentEls = $(this).closest(input)
.map(function() {
solid += this.value;
return this.value;
})
.get()
.join( ", " );
console.log(parentEls);
});
solid += '}';
$( ".submit_json" ).html(solid);
});
You need to use .parents(), not .closest() so you get all the containing elements.
Then create containing properties with those names when necessary.
$("#btn_createservice").on("click", function() {
var svc_obj = {};
$(".node:checked").each(function() {
var cur_obj = svc_obj;
$(this).parents(".node").map(function () {
return this.value;
}).get().reverse().forEach(function(name) {
if (!cur_obj[name]) { // create property if it doesn't already exist
cur_obj[name] = {};
}
cur_obj = cur_obj[name]; // use this for next iteration;
});
var thisname = this.name.match(/\[([^[])+\]$/)[1]; // Get property name from name="sub_root[...]"
cur_obj[thisname] = this.value;
});
$(".submit_json").html(JSON.stringify(svc_obj));
})
You need to fix the HTML you're creating so that the checkboxes have value='" + info[k] "'.

Get cascading data from form into JSON object

I am trying to build a 'form builder' where you can add sub-fields to fields, and sub-fields to those sub-fields, etc. I have that part working and the output html I have pasted here on pastebin
Which looks like:
I need to get the data into this format:
var form_structure = {
iGA2cXN3XXdmr1F: {
title: "Field 1",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.1",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.2",
help: "",
placeholder: "",
type: "text",
options: []
},
m8r32skADKsQwNt: {
title: "Field 1.3",
help: "",
placeholder: "",
type: "text",
options: [],
subfields: {
m8r32skADKsQwNt: {
title: "Field 1.3.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
}
},
aBvXXN3XXdmr1F: {
title: "Field 2",
help: "",
placeholder: "",
type: "multi-select",
options: {"123QWE": "Opt 1", "ASDZXC": "Opt 2", "ASDQWE": "Opt 3"},
subfields: {
m8r32skADKsQwNt: {
title: "Field 2.1",
help: "",
placeholder: "",
type: "text",
options: []
}
}
}
};
I have tried (sorry for the bad formatting):
function buildRequestStringData(form) {
var select = form.find('select'),
input = form.find('input'),
options_arr = [],
obj = {},
requestString = '{';
for (var i = 0; i < select.length; i++) {
if(typeof $(select[i]).data('parentid') != 'undefined') {
// has parent
if($(select[i]).data('parentid') != $(select[i]).data('mainid')) {
requestString += '"' + $(input[i]).data('mainid') + '":"' + JSON.stringify(buildRequestStringData()) + '",';
}
} else {
// does not have parent
requestString += '"' + $(select[i]).attr('name') + '": "' +$(select[i]).val() + '",';
}
}
// if (select.length > 0) {
// requestString = requestString.substring(0, requestString.length - 1);
// }
for (var i = 0; i < input.length; i++) {
// if ($(input[i]).attr('type') !== 'checkbox') {
requestString += '"' + $(input[i]).attr('name') + '":"' + $(input[i]).val() + '",';
// } else {
// if ($(input[i]).attr('checked')) {
// requestString += '"' + $(input[i]).attr('name') +'":"' + $(input[i]).val() +'",';
// }
// }
}
if (input.length > 0) {
requestString = requestString.substring(0, requestString.length - 1);
}
requestString += '}]';
return requestString;
}
The best way I have been able to be close to this is on this fiddle - but that only allows me to put the id down, and does not format it into the format I need.
What is the best way to do this?
I think you're on the right track. See if you can nest your HTML in the same structure you want for your JSON, then when harvesting the details for each item, walk up the DOM tree grabbing each parent's id until you get to the form, and then create / append to the nested JSON object the data you find. If this isn't descriptive enough, I'll mod the answer to include html and js examples.

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

autocomplete does not get selected

Number of autocomplete search box is dynamic based an #AddButton. Autocomplete is working, but when I select the values, it doesnt rendered it properly. Please tell me where Am I missing.
Fiddle setup is at http://jsfiddle.net/jakenrush/kELm3/1/
Jquery code below
$(function() {
var projects = [
{
"label": "ajax",
"value": "1003",
"desc": "foriegn"
},
{
"label": "jquery",
"value": "1000",
"desc": "dd"
},
{
"label": "wordpress theme",
"value": "1000",
"desc": "h"
},
{
"label": "xml",
"value": "1000",
"desc": "j"
}];
$("#addButton");
var counter = 13;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'project-description' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'project' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'project-id' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#project" + counter).autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project" + counter).val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project" + counter).val(ui.item.label);
$("#project-id" + counter).val(ui.item.value);
$("#project-description" + counter).val(ui.item.value);
$("#project-icon" + counter).attr("src", "images/" + ui.item.icon);
return false;
}
})
counter++;
});
});
html code :
<div id="project-label"></div>
<input type="hidden" id="project-id" />
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
</div>
</div>
<input type='button' value='Add' id='addButton' />
i have update your fiddle and it is working, the problem is with your counter variable which never been incremented, because you have place at end of script, but you have return statement above it.
your fiddle here http://jsfiddle.net/kELm3/6/
var counter = 0;
$("#addButton").click(function() {
counter++;

Fetching a json from jsp and displaing on javascript

I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);

Categories

Resources