File reader API gives no out put on AUDIO files - javascript

As a part of a before upload control, I check if added files actually match the filetype that their extension describes.
I do a filecheck using a hidden element. and if it fails, it gets removed after formdata append.
I check the files at the backend too, but I also want to check via File Reader process. All functions like createItems or readItems and so on, are working in all other cases, meaning that they return output of either null, true or false. While I get output from image and video files, audio files not at all. It should work.
The question is: Does the file reader read audio files differently compared to video and image files?
The following is only a tiny block of the actual code.
Now the question is: Why it doesn't return output on audio files?.
quest0 & quest1 are UI elements. Which is the element that I pull the files from.
reader is "new FileReader".
what.filecount is added while page init as readonly property.
readItems gives output on all kind off files,
However the UI html doesn't get updated if it is the file type is audio/?
for (var oD = 0; oD < what.files.length; oD++)
{
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) { return; }
if (file_s.exec(file) && !what.multiple) { pL = true; }
else
{
if (what.files.length > what.filecount)
{
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null)
{ quest0.innerHTML = ('too many files added. only ' + what.filecount + ' are allowed.'); }
return;
}
pL = true;
if ( !lastform.includes(what.form.id) ) { pL = false; }
}
if (what.files && what.files[oD] && pL == true)
{
if (file_prev != null)
{
if (file_prev.getAttribute('data-src') == '')
{file_prev.setAttribute('data-src', file_prev.src); }
file_prev.src = file_backsrc;
}
reader.onload = function(e)
{
init();
if (typeof file_prev === 'undefined')
{
if (quest1 != null) { quest1.innerHTML = 'Error occoured'; }
return;
}
if (file_p == 'img' || file_p == 'video' || file_p == 'audio')
{ file_prev.src = e.target.result; }
if (file_p == 'canvas') { /*not yet*/ }
kill.classList.remove('invisible');
if (quest1 != null) { quest1.innerHTML = 'file done'; }
}
reader.onerror = function(e)
{
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
}
function waitfor(arr)
{
if (arr == null || arr.length == 0) { return; }
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null)
{ quest1.innerHTML = 'processing ' + file_p; }
}
if (what.multiple)
{
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++)
{
var oB = what.files[oD], oB0, oB1;
if (oB.type.includes('im')) { file_p = 'img'; }
if (oB.type.includes('au')) { file_p = 'audio'; }
if (oB.type.includes('vi')) { file_p = 'video'; }
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount)
{
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null)
{
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name))
{
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
}
}
}
}
if (stoargearr.length == what.files.length) { waitfor(stoargearr); }
else { reader.readAsDataURL(what.files[oD]); }
}
}
}
Does the "File reader API" react different on audio files as it does on video or image files?
Thanks for any help.

here it goes.
for (var oD = 0; oD < what.files.length; oD++) {
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) {
return;
};
if (file_s.exec(file) && !what.multiple) {
pL = true;
} else {
if (what.files.length > what.filecount) {
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null) {
quest0.innerHTML = 'too many files added. only ' + what.filecount + ' are allowed.';
};
return;
};
pL = true;
if (!lastform.includes(what.form.id)) {
pL = false;
};
};
if (what.files && what.files[oD] && pL == true) {
if (file_prev != null) {
if (file_prev.getAttribute('data-src') == '') {
file_prev.setAttribute('data-src', file_prev.src);
};
file_prev.src = file_backsrc;
};
reader.onload = function(e) {
init();
if (typeof file_prev === 'undefined') {
if (quest1 != null) {
quest1.innerHTML = 'Error occoured';
};
return;
};
if (file_p == 'img' || file_p == 'video' || file_p == 'audio') {
file_prev.src = e.target.result;
};
if (file_p == 'canvas') { /*not yet*/ };
kill.classList.remove('invisible');
if (quest1 != null) {
quest1.innerHTML = 'file done';
};
};
reader.onerror = function(e) {
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
};
function waitfor(arr) {
if (arr == null || arr.length == 0) {
return;
};
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
};
if (what.multiple) {
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++) {
var oB = what.files[oD],
oB0, oB1;
if (oB.type.includes('im')) {
file_p = 'img';
};
if (oB.type.includes('au')) {
file_p = 'audio';
};
if (oB.type.includes('vi')) {
file_p = 'video';
};
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount) {
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null) {
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name)) {
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
};
};
};
};
if (stoargearr.length == what.files.length) {
waitfor(stoargearr);
};
} else {
reader.readAsDataURL(what.files[oD]);
};
};
};```

if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
This block gives no output on audio files.

Related

null coalescing a JsonConvert in javascript

I have a script that looks like this
Item i = db.Items.Find(Model.ItemID);
Component comp = db.Components.Find(Model.ComponentID);
<script type="text/javascript">
function clicked(e) {
var comp = #Html.Raw(JsonConvert.SerializeObject(comp.ComponentID)) || null;
var item = #Html.Raw(JsonConvert.SerializeObject(i.ItemID)) || null;
var compFSTK = #Html.Raw(JsonConvert.SerializeObject(comp.FSTK)) || null;
var itemFSTK = #Html.Raw(JsonConvert.SerializeObject(i.FSTK)) || null;
if (item == null) {
alert('item is null');
}
if (comp == null) {
alert('comp is null');
}
if(comp != null && item == null) {
var compQty = $('#compQTY').val();
var compDiff = #Model.comp_qty - compQty;
var compFuture = compFSTK - compDiff;
if (!confirm('Are you sure? Doing this will reduce component ' + comp.ComponentID + ' future stock to ' + compFuture))e.preventDefault();
}
else if(item!== null && comp == null ) {
var itemQty = $('#itemQTY').val();
var itemDiff = #Model.item_qty - itemQty;
var itemFuture = itemFSTK - itemDiff;
if (!confirm('Are you sure? Doing this will reduce item ' + item.ItemID + ' future stock to ' + itemFuture))e.preventDefault();
}
<script>
But whenever comp or i is null and is deserialized I receive the error of 'i/comp is null'
how can I make it so that it just sets the variable to null if it is null?

Why is win undefined?

I wrote this in javascript to chat. Now I can call openChat with clicking a button and that works. But if I call it from onmessage-event, I get the
error: Uncaught TypeError: Cannot read property 'document' of
undefined
I'm new to javascript and I don't know, why I get this error?. Can somebody maybe help me?
Thanks:)
Thats the code:
var app = new Vue({
el: '#app',
data: {
busy: false,
roomId: 'POWebinar',
joinedRoom: false,
chatWirCB: false,
chatKundenCB: false,
microphoneWirCB: false,
microphoneKundenCB: false,
user: 'Benutzer',
},
methods: {
openChat: function () {
console.log("in fkt openChat");
win = window.open('', 'myconsole',
'scrollbars=1, width=450,height=500'
+ ',menubar=1'
+ ',toolbar=1'
+', location=1'
+ ',resizable=1')
win.document.writeln("<head><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'></head><body style='background-color:#ecf0f1'></body>");
chat = document.getElementById("chatHtml").innerHTML;
win.document.write(chat);
win.document.title = "PatOrg - Live Chat";
win.document.getElementById('input-text-chat').onkeyup = function (e) {
if (e.keyCode != 13) return;
// removing trailing/leading whitespace
this.value = this.value.replace(/^\s+|\s+$/g, '');
var a = new Date();
var b = a.getHours(); var c = a.getMinutes(); var d = a.getSeconds();
if (b < 10) { b = '0' + b; }
if (c < 10) { c = '0' + c; }
if (d < 10) { d = '0' + d; }
var time = b + ':' + c + ':' + d;
if (!this.value.length) return
console.log(this.value);
connection.send('<div id="chatSend" class="chat-OutputGET bubbleGET"> <font color="white">' + username + '(' + time + '): ' + this.value + '</font></div>');
console.log(username);
console.log('User (' + time + '): ' + this.value);
appendDIV('<div id="chatGet" class="chat-OutputSEND bubble"> <font color="white"> Ich (' + time + '): ' + this.value + '</font></div>');
this.value = '';
};
var chatContainer = win.document.getElementById('chat-output');
function appendDIV(event) {
if (event == "turnMicroOff" || event.data == "turnMicroOff" || event == "turnMicroOn" || event.data == "turnMicroOn" || event == "turnChatOn" || event.data == "turnChatOn" || event == "turnChatOff" || event.data == "turnChatOff") {
if (event == "turnMicroOff" || event.data == "turnMicroOff") {
console.log("audioID: " + audioID);
console.log("audioID: " + audioID);
for (i = 0; i < audioID.length; i++) {
connection.streamEvents[audioID[i]].stream.mute('audio');
}
}
else if (event == "turnMicroOn" || event.data == "turnMicroOn") {
console.log("audioID: " + audioID);
console.log("audioID: " + audioID);
for (i = 0; i < audioID.length; i++) {
connection.streamEvents[audioID[i]].stream.unmute('audio');
}
}
else if (event == "turnChatOn" || event.data == "turnChatOn") {
document.getElementById("btnChatOpen").style.visibility = "visible";
}
else if (event == "turnChatOff" || event.data == "turnChatOff") {
document.getElementById("btnChatOpen").style.visibility = "hidden";
}
}
else {
var div = document.createElement('div');
div.innerHTML = event.data || event;
chatContainer.appendChild(div);
div.tabIndex = 0;
div.focus();
win.document.getElementById('input-text-chat').focus();
emojify.run(win.document.getElementById('chat-output'));
}
}
connection.onmessage = appendDIV;
}
}
})
connection.onmessage = function (event) {
console.log(event.data);
if (event == "turnMicroOff" || event.data == "turnMicroOff") {
for (i = 0; i < audioID.length; i++) {
console.log("audioID: " + audioID[i]);
connection.streamEvents[audioID[i]].stream.mute('audio');
}
}
else if (event == "turnMicroOn" || event.data == "turnMicroOn") {
app.openChat();
for (i = 0; i < audioID.length; i++) {
console.log("audioID: " + audioID[i]);
connection.streamEvents[audioID[i]].stream.unmute('audio');
}
}
else if (event == "turnChatOn" || event.data == "turnChatOn") {
document.getElementById("btnChatOpen").style.visibility = "visible";
}
else if (event == "turnChatOff" || event.data == "turnChatOff") {
document.getElementById("btnChatOpen").style.visibility = "hidden";
}
}

Preventing URL string from being encoded in JavaScript

I'm not very good at JavaScript and have some code that was written for me:
if (args[2].LocationCacheTypeID == 1) {
locationInput.name = 'Cities';
I'd like to add LinkID=27201& to the code as seen below:
if (args[2].LocationCacheTypeID == 1) {
locationInput.name = 'LinkID=272081&Cities';
The only problem is that when I add it and it's turned into a URL string the result is:
?LinkID%3D272081%26Cities=Poquoson
It turns the = to %3D and the & to %26.
How can I fix this?
The full original script is:
<script type='text/javascript'>
(function() {
var dataSource = new YAHOO.util.ScriptNodeDataSource('http://api.idx.diversesolutions.com/API/Locations/33266/81?');
var ac = new YAHOO.widget.AutoComplete('vrcsf_location', 'vrcsf_location_ac', dataSource);
dataSource.responseSchema = {
resultsList: '',
fields: ['LocationName','LocationCacheTypeID','TotalCount']
};
ac.animVert = false;
ac.queryMatchContains = true;
ac.queryQuestionMark = false;
ac.useShadow = true;
ac.queryDelay = .1;
ac.typeAhead = false;
ac.allowBrowserAutocomplete = false;
ac.alwaysShowContainer = false;
ac.resultTypeList = false;
ac.maxResultsDisplayed = 5;
ac.resultTypeList = false;
ac.generateRequest = function(query) {
return 'partialName=' + query + '&maxAreasToReturn=5';
};
ac.formatResult = function(resultData, query, resultMatch) {
var type;
if (resultData.LocationCacheTypeID == 1) {
type = 'City';
} else if (resultData.LocationCacheTypeID == 2) {
type = 'Community';
} else if (resultData.LocationCacheTypeID == 3) {
type = 'Tract';
} else if (resultData.LocationCacheTypeID == 4) {
type = 'Zip';
} else if (resultData.LocationCacheTypeID == 5) {
type = 'County';
}
return (resultMatch + ' (' + type + ')');
};
ac.itemSelectEvent.subscribe(function(e, args) {
var locationInput = YAHOO.util.Dom.get('vrcsf_location');
if (args[2].LocationCacheTypeID == 1) {
locationInput.name = 'Cities';
} else if (args[2].LocationCacheTypeID == 2) {
locationInput.name = 'Communities';
} else if (args[2].LocationCacheTypeID == 3) {
locationInput.name = 'Tracts';
} else if (args[2].LocationCacheTypeID == 4) {
locationInput.name = 'ZipCodes';
} else if (args[2].LocationCacheTypeID == 5) {
locationInput.name = 'Counties';
}
});
})();

How to import data of gmail contacts, using javascript Google Contact API, in more detailed format?

I'm using code from this page http://code.google.com/apis/contacts/docs/1.0/developers_guide_js.html to get list of gmail contacts. Actually it works ok, but I get data of name, address, etc like a simple string, with "\n" as separator, for example:
<script type="text/javascript">
var contactsService;
var scope = 'https://www.google.com/m8/feeds';
function setupContactsService() {
//contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full'; //?max-results=9999&alt=json&v=3.0
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var addrs = entry.getPostalAddresses();
var name = entry.getTitle();
// logging
console.log(addrs[0]);
console.log(name);
}
}
function handleError(e) {
alert(e.cause ? e.cause.statusText : e.message);
}
</script>
it gives me an object where name and address values are simple strings.
Can I get somehow data in like associative array format, where address will contains separate values of street, zip, city, country; and name separate values of first name, last name etc.
Like:
{
"type": "address",
"value":
{
"street": "Starret 1234",
"city": "City name",
"stateOrProvince": "ca",
"postalCode": "73000",
"country": "USA"
}
},
{
"type": "name",
"value":
{
"firstName": "Allen",
"lastName" : "Iverson",
.....
}
}
Thanks in advance!
Seems I found an answer, for get more detailed and formatted info need to add additional parameter to contactsFeedUri for google.gdata.contacts.ContactQuery.
This additional parameter is: ?v=3.0
So in my case function will looks like:
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
And for get necessary data I create a simple obj, which can be useful for somebody:
function contactEntry(entry) {
this.entry = entry;
this.testEntry = function() {
alert( 'test entry' )
};
this.getFirstName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$givenName == null) || (entry.gd$name.gd$givenName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$givenName.$t;
}
};
this.getLastName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$familyName == null) || (entry.gd$name.gd$familyName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getAdditionalName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$AdditionalName == null) || (entry.gd$name.gd$AdditionalName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getEmail = function() {
if ((entry.gd$email == null) || (entry.gd$email.length == 0) || (entry.gd$email[0].address == null)) {
return '';
} else {
return entry.gd$email[0].address;
}
};
this.getStreet = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$street == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$street.$t;
}
};
this.getCity = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$city == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$city.$t;
}
};
this.getCountry = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$country == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$country.$t;
}
};
this.getPostcode = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$postcode == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$postcode.$t;
}
};
this.getPhone = function() {
if ((entry.gd$phoneNumber == null) || (entry.gd$phoneNumber.length == 0) || (entry.gd$phoneNumber[0].$t == null)) {
return '';
} else {
return entry.gd$phoneNumber[0].$t
}
};
this.getOrganization = function() {
if ((entry.gd$organization == null) || (entry.gd$organization.length == 0) || (entry.gd$organization[0].getOrgName() == null)) {
return '';
} else {
return entry.gd$organization[0].getOrgName().getValue();
}
};
this.getBirthday = function() {
if ((entry.gContact$birthday == null) || (entry.gContact$birthday.when == null)) {
return '';
} else {
return entry.gContact$birthday.when;
}
};
this.getEvent = function() {
if ((entry.gContact$event == null) || (entry.gContact$event.length == 0) || (entry.gContact$event[0].gd$when == null)) {
return '';
} else {
return entry.gContact$event[0].gd$when.startTime;
}
};
// protected methods
this._addrExists = function() {
if ((entry.gd$structuredPostalAddress == null) || (entry.gd$structuredPostalAddress.length == 0)) {
return false;
}
return true;
};
}
It can be used in this way:
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
var contact = new contactEntry(entries[0]);
var address = {};
address['fname'] = contact.getFirstName();
address['lname'] = contact.getLastName() + (contact.getAdditionalName() != '' ? ' ' + contact.getAdditionalName() : '');
address['address'] = contact.getStreet();
address['city'] = contact.getCity();
address['country'] = contact.getCountry();
address['zip'] = contact.getPostcode();
address['phone'] = contact.getPhone();
address['mail'] = contact.getEmail();
address['organization'] = contact.getOrganization();
address['birthday'] = contact.getBirthday();
address['event'] = contact.getEvent();
}

Optimizing the IF condition

AddPatient = {};
if(GenderValue === undefined) {
AddPatient.Gender = ' ';
} else {
AddPatient.Gender = GenderValue;
}
if(DateOfBirthValue === undefined) {
AddPatient.DateOfBirth = ' ';
} else {
AddPatient.DateOfBirth = DateOfBirthValue;
}
if(SSNValue === undefined) {
AddPatient.SSN = ' ';
} else {
AddPatient.SSN = SSNValue;
}
if(RaceValue === undefined) {
AddPatient.Race = ' ';
} else {
AddPatient.Race = RaceValue;
}
if(ReligionValue === undefined) {
AddPatient.Religion = ' ';
} else {
AddPatient.Religion = ReligionValue;
}
if(CellPhoneValue === undefined) {
AddPatient.CellPhoneNumber1 = ' ';
} else {
AddPatient.CellPhoneNumber1 = CellPhoneValue;
}
if(HomePhoneValue === undefined) {
AddPatient.phonenumber1 = ' ';
} else {
AddPatient.phonenumber1 = HomePhoneValue;
}
if(PrimaryPhoneValue === undefined) {
AddPatient.PrimaryPhoneNumber = ' ';
} else {
AddPatient.PrimaryPhoneNumber = PrimaryPhoneValue;
}
if(EmailValue === undefined) {
AddPatient.EmailAddress1 = ' ';
} else {
AddPatient.EmailAddress1 = EmailValue;
}
AddPatient.ResidentialAddress = {};
if(AddressValue === undefined) {
AddPatient.AddressLine1 = ' ';
} else {
AddPatient.ResidentialAddress.AddressLine1 = AddressValue;
}
if(CityValue === undefined) {
AddPatient.City = ' ';
} else {
AddPatient.ResidentialAddress.City = CityValue;
}
if(StateValue === undefined) {
AddPatient.State = ' ';
} else {
AddPatient.ResidentialAddress.State = StateValue;
}
if(ZipValue === undefined) {
AddPatient.PostalCode = ' ';
} else {
AddPatient.ResidentialAddress.PostalCode = ZipValue;
}
Is there any better way to write the same code?
You can write
AddPatient.Gender = GenderValue || " ";
The || operator returns the left-most "truthy" operand, so this will evaluate to " " if GenderValue is "falsy" (such as undefined, false, "", 0, or null)
function isDefined(value){
if(value != null)
return value;
else
return ' ';
}
AddPatient = {};
AddPatient.Gender =isDefined(AddPatient);
and son on
Here is a suggestion to what you actually asked:
http://jsfiddle.net/mplungjan/b5yRw/
It will of course work with a form instead.
var GenderValue = "F";
var DateOfBirthValue; // undefined
var AddressValue = "some street";
// var CityValue; // undeclared
function addItem(obj,varName) {
obj[varName] = window.hasOwnProperty(varName+"Value")?window[varName+"Value"]||"not set":"not declared";
}
function addItemLoop(obj) {
for (var o in obj) {
if (typeof obj[o] === 'object') {
addItemLoop(obj[o]);
}
else {
addItem(obj, o);
}
}
}
AddPatient = {
Gender : " ",
DateOfBirth: " ",
ResidentialAddress : {
Address:" ",
City: " "
}
}
addItemLoop(AddPatient);
document.write("<br/>Gender (F):"+AddPatient.Gender);
document.write("<br/>DOB (not set):"+AddPatient.DateOfBirth);
document.write("<br/>ResidentialAddress Address (some street):"+AddPatient.ResidentialAddress.Address);
document.write("<br/>ResidentialAddress City (not declared):"+AddPatient.ResidentialAddress.City);
Previous answer
Not better but shorter using the ternary operator
AddPatient.Gender = (GenderValue === undefined)? " ":GenderValue;
or shortcut
AddPatient.Gender = GenderValue || " ";
Note - In the shortcut you WILL get a space if value is 0
In EITHER you will get an error if GenderValue has not been declared.
So somewhere you need a var GenderValue;
Example:
var b="hello", c;
var a = {}
a.x = b||"no b"
a.y = (c===undefined)? "no c here":c
a.z = c || "no c here either"
alert(a.x)
alert(a.y)
alert(a.z)
Here's one option:
function SetOrDefault(value, property) {
if (typeof(value) == 'undefined' || value == null) {
property = ' ';
}
else {
property = value;
}
}
And then call it like this:
SetOrDefault(GenderValue, AddPatient.Gender);

Categories

Resources