Finding text to compare true or false - javascript

I'm trying to build out a json object in javascript/jquery that compares . Here's what I have
html:
<div class="field">
<div>size</div>
<div>large</div>
<div>medium</div>
<div>number</div>
</div>
js:
selectedObj = {
'fieldSize':false,
'sizeXSmall':false,
'sizeSmall':false,
'sizeMedium':false,
'sizeLarge':false,
'sizeXLarge':false,
'fieldName':false,
'fieldNum':false
};
if(jQuery('.field div:contains("size")')){selectedObj['fieldSize'] = true}
if(jQuery('.field div:contains("xs")')){selectedObj['sizeXSmall'] = true}
if(jQuery('.field div:contains("small")')){selectedObj['sizeSmall'] = true}
if(jQuery('.field div:contains("medium")')){selectedObj['sizeMedium'] = true}
if(jQuery('.field div:contains("large")')){selectedObj['sizeLarge'] = true}
if(jQuery('.field div:contains("xl")')){selectedObj['sizeXLarge'] = true}
if(jQuery('.field div:contains("name")')){selectedObj['fieldName'] = true}
if(jQuery('.field div:contains("number")')){selectedObj['fieldNum'] = true}
So ideally I would end up with an object that looks like this:
selectedObj = {
'fieldSize':true,
'sizeXSmall':false,
'sizeSmall':false,
'sizeMedium':true,
'sizeLarge':true,
'sizeXLarge':false,
'fieldName':false,
'fieldNum':true
};
I instead end up with an object where everything is true. Here is an example:
http://jsfiddle.net/vz600nd7/
Also, when I console log it before an after it looks like this:
It looks like the 'preview' is giving the right info but the actual view is not.

As I said in the comments, jQuery(selector) will return a jQuery object which will always be a truthy value. So your if condition will get executed every time.
I will try something like
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
var map = {
'fieldSize': 'size',
'sizeXSmall': 'xs',
'sizeSmall': 'small',
'sizeMedium': 'medium',
'sizeLarge': 'large',
'sizeXLarge': 'xl',
'fieldName': 'name',
'fieldNum': 'number'
};
selectedObj = {
'fieldSize': false,
'sizeXSmall': false,
'sizeSmall': false,
'sizeMedium': false,
'sizeLarge': false,
'sizeXLarge': false,
'fieldName': false,
'fieldNum': false
};
var $els = jQuery('.field div');
$.each(map, function(key, value) {
selectedObj[key] = $els.is(':contains("' + value + '")')
});
log('After: ' + JSON.stringify(selectedObj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="field">
<div>size</div>
<div>large</div>
<div>medium</div>
<div>number</div>
</div>
<div id="log"></div>

if you want to detect, if object exists, use:
if($('.field div:contains("size")')[0]) selectedObj['fieldSize'] = true;
...

Related

select item by text with jshjohnson choices

How to realize selection of an item from choices element using jshjohnson choices library.
Code:
let vehicleModel = document.getElementById('vehicleModel');
let choiceProps = {
renderChoiceLimit: -1,
maxItemCount: -1,
silent: false,
removeItems: false,
editItems: false,
searchEnabled: true,
searchFields: 'label',
searchResultLimit: 6,
itemSelectText: 'Кликните для выбора',
classNames: {
listSingle: 'form-control pl-3',
containerInner: 'p-0'
},
};
const modelChoices = new Choices(vehicleModel, choiceProps);
let models = []; // I get the values from axios to pass them as paramater
modelChoices.setChoices(models, 'value', 'label', false);
After I initiated choices element in another part of code i have to select a value with autofilling function
const fillModelWithValue = (modelName) => {
let modelCoices = document.getElementById('vehicleModel').setChoiceByValue(modelName);
}
This code doesn't work. But how can I realize this functionality?

Vue.js not updating automatically

I have got this in my html code
<div class="pl_wrapper">
<div class="options_pl">
<input type="button" #click="optionButtonClicked" class="option_button_pl" value="List">
<input type="button" #click="optionButtonClicked" class="option_button_pl" value="Add a language">
</div>
{{show2}}
</div>
And this in my vue.js
const ProgrammingLanguages = new Vue({
el:".pl_wrapper",
data:{
name: "aa",
show1: false,
show2: false
},
methods: {
optionButtonClicked(){
var indexOfClicked = index(event.target,event.target.className);
var equalIndexOfDiv = getOnIndex(indexOfClicked,"pl_divs")
$(".options_pl").hide();
show1 = (indexOfClicked==0) ? true : false
show2 = (indexOfClicked==1) ? true : false
}
}
});
Now when i click option_button_pl i expect {{show2}}'s to also change from false to true and vice versa.But alas that doesn't Jsfiddle: happen.https://jsfiddle.net/3akfzcyf/
you have to use the this keyword. Something like this.show1 and this.show2
here is your code working and I updated your fiddle
Adding the this statement and adding the event param inside optionButtonClicked
const ProgrammingLanguages = new Vue({
el:".pl_wrapper",
data:{
name: "aa",
show1: false,
show2: false
},
methods: {
optionButtonClicked(event){
var indexOfClicked = index(event.target,event.target.className);
this.show1 = (indexOfClicked==0) ? true : false
this.show2 = (indexOfClicked==1) ? true : false
console.log(this.show2)
}
}
});
function index(element,className){
var allElements = document.getElementsByClassName(className);
for (var i = 0; i < allElements.length; i++) {
if(allElements[i]==element){
return i;
}
}
}

JSON response received in AJAX success but not parsing

I have the following AJAX function below. The problem is that I get the correct response headers in the success function of AJAX but when I parse the response I get undefined.
The JSON data that I receive is like following:
[{"responseCode":1,"msg":"Successfully done!"}]
JS
// Renaming am item
filelist.on('click', '.btn-rename', function(){
var that = this; //Save the scope of the button that was clicked
var id = $(this).data('id');
var name = $(this).data('filename');
var jc = $.confirm({
theme: 'black',
type: 'dark',
typeAnimated: true,
title: 'Rename this file?',
icon: 'fa fa-pencil-square-o',
content: '<input id="newName" type="text" value="'+name+'"/><span id="response"></span>',
onOpen: function() {
var element = $('#newName');
element.focus();
element.select();
},
buttons: {
save: {
text: 'Rename',
btnClass: 'btn-dark',
action: function() {
this === jc;
var inputName = $('#newName').val();
if(inputName == '') {
$('#response').html('Please enter a new name..').addClass('responseAlert');
return false;
}
else
if(inputName == name) {
$('#response').html(' C'mon! Don't be silly..').addClass('responseWarning');
return false;
}
//Send request to update the name
$.ajax({
type:"POST",
url:"rename.php",
data: {
fileId: id,
newName: inputName
},
beforeSend: function() {
$('#response').html('<i class="fa fa-spinner fa-spin" aria-hidden="true"></i> Working on it...').addClass('responseProcessing');
},
success: function(data){
var obj = JSON.parse(data);
var status = obj.responseCode;
alert(obj.responseCode);
if(status == 1) {
jc.close();
$.alert({
theme: 'black',
icon: 'fa fa-check',
title: 'Success',
type: 'green',
typeAnimated: true,
content : response.msg
});
}
else {
$('#response').html(response.msg).addClass('responseAlert');
}
}
});
return false;
}
},
cancel: {
}
}
});
return false;
});
When the response is parsed, it converted to JSON Array with that object indexed as the first element. Note the brackets [] are causing this.
var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object]
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}
var a = JSON.parse('[{"responseCode":1,"msg":"Successfully done!"}]');
console.log(a); // [Object]
console.log(a[0]); // {"responseCode":1,"msg":"Successfully done!"}
Whereas parsing a string without brackets results in desired object
var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"}
var a = JSON.parse('{"responseCode":1,"msg":"Successfully done!"}');
console.log(a); // {"responseCode":1,"msg":"Successfully done!"}
You need to have to remove those brackets from your back-end.
If you specify dataType:"text", then the response Will ne not parsed.
The problem with tour expectation is that you try to access property of an array:
var data = "[{"responseCode":1,"msg":"Successfully done!"}]"
var obj = JSON.parse(data)
// and then:
console.log(obj[0]. responseCode)
obj is an array! (Or remove e Square brakets!)

Binding non-boolean values to CheckBox in Table

I am having trouble to bind a String value of 00 and 98 to false and true. I have found quite a few possible solutions but none of them works for me and I don't quite understand why.
Suppose I receive data from a server and create a JSON Model and set that to the table model.
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
var statusTemplate = new sap.ui.commons.CheckBox({
editable: false,
// THIS WAS MY FIRST ATTEMPT TO GET IT WORKING
//checked: {
// path: "{TableModel>status}",
// formatter: function(val) {
// console.log(val);
// return val === "98";
// }
//}
});
// SECOND ATTEMPTS, DOESN'T WORK EITHER
statusTemplate.bindProperty("checked", "{TableModel>status}", function(val) { return val === "98"; });
for(var i = 0; i < columns.length; i++) {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
Both ways in the code above do not work. I don't know whether it is the logic or whether I am using the model wrong. Every other (TextView) Column displays data to which it is bound... so I believe that the binding is correct!?
I also have tried this way but that doesn't work at all for me: OpenUI5 binding property with a function, instead of direct access
I keep on getting the error that "00" is not a valid value for the checkbox.
Am I doing something obviously wrong?
EDIT: Current state
This function is basically called everytime the user switches
the table in the application. The old data (rows and columns) will be
deleted and filled new. The parameter columns contains an array of
strings of the column names! No data is in the data model yet!!!
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
oTable.destroyColumns();
sap.ui.getCore().setModel(null, "TableModel");
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
checked: {
path: "{TableModel>status}",
formatter: function(v) {
console.debug(v);
if(v === "98") return true;
else return false;
}
}
});
for(var i = 0; i < columns.length; i++) {
if(columns[i] !== 'rowid') {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusCheckBoxTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
}
After a user selected a table to display it sits there only displaying
the columns. Data is fetched from the server (ajax call) as an JSON object and a data model is created. It all works fine. Data is bound without problems and displayed correctly.
function tableBtnReloadPressed() {
// ajax call
var tabledata = readTableData(ACTIVE_TABLE);
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData(tabledata);
sap.ui.getCore().setModel(oModel, "TableModel");
var oTable = sap.ui.getCore().byId("mainTable");
oTable.setModel(oModel);
oTable.bindRows("TableModel>/");
}
EDIT: Third try with factory
function createTableColumns(columns) {
var oTable = sap.ui.getCore().byId("mainTable");
oTable.destroyColumns();
sap.ui.getCore().setModel(null, "TableModel");
sap.ui.model.SimpleType.extend("BooleanStringType", {
formatValue: function(s) {
console.debug(typeof s, s);
return s === "98";
},
parseValue: function(s) {
console.debug(typeof s, s)
return s ? "98" : "00";
},
validateValue: function(s) {
console.debug(typeof s, s)
}
});
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
//checked: {
// path: "{TableModel>status}",
// formatter: function(v) {
// console.debug(v);
// if(v === "98") return true;
// else return false;
// }
//}
});
statusCheckBoxTemplate.bindProperty("checked", {
path: "{TableModel>status}",
type: new BooleanStringType()
});
for(var i = 0; i < columns.length; i++) {
if(columns[i] !== 'rowid') {
oTable.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: columns[i]}),
name: columns[i],
flexible: false,
autoResizable: true,
template: columns[i] === 'status' ? statusCheckBoxTemplate : new sap.ui.commons.TextView({text: "{TableModel>" + columns[i] + "}"}),
sortProperty: columns[i],
filterProperty: columns[i],
}));
}
}
}
You should simplify to get it working. First thing is to use a textview / label to check if the binding is working. Only then change to the checkbox and use a formatter / custom datatype for the conversion.
For instance, this is not valid (from the code above):
checked: {
path: "{TableModel>status}",
because when you pass an explicit path property, you should not use the {} in the string.
Ok, I put this into jsbin and played arount wiht it a bit. jsbin with solution
The correct template for the checkbox is this:
var statusCheckBoxTemplate = new sap.ui.commons.CheckBox({
text: "{TableModel>status}",
editable: false,
checked: {
path: "TableModel>status",
formatter: function(v) {
return(v === "98");
}
}
});
Edit: #jumpifzero beat me to it. But I wanted to edit my post for a complete picture. Such an easy to miss answer. ^^"

selectize js use array as source

Hi I am getting back a JSON encoded array ("html") from my Ajax call that I would like to add in the selectize as both value and text (I am using a tag) .
How can I do that ?
HTML
<input type="text" value="test" class="demo-default selectized" id="input-tags" tabindex="-1" style="display: block;">
JQUERY
try {
data = $.parseJSON(html);
var obj = jQuery.parseJSON(html);
outcome = (obj.outcome);
$('#input-tags').selectize({
delimiter: ',',
persist: false,
maxItems: 1,
create: function (input) {
return {
value: input,
text: input
}
}
});
}
You could map the array onto an array of objects, like this:
data = $.parseJSON(html);
var items = data.map(function(x) { return { item: x }; });
Then use "labelField" and "valueField" to specify the text/value:
$('#input-tags').selectize({
delimiter: ',',
persist: false,
options: items,
labelField: "item",
valueField: "item"
});
Fiddle Demo.
With ES6 you can reduce your oneliner a bit
const items = data.map(item => ({item}));

Categories

Resources