convert object to string in Javascript - javascript

UPDATED QUESTION
here is my code :
function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
$("#CXACNUM").val($("#CXACNUM").val("Data5"));
$("#CXACNAM").val($("#CXACNAM").val("Data4"));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
Data4 and Data5 is a field inside the database. these need to be display in the textbox. however as previous, it return output at the textbox as below :
Object Object

However when it display, it give me output :
[Object object]
This is because you are setting the returned value of val back to the same input, which is a jquery object
You need to simply do
$("#CXACNUM").val( JSON.stringify( Data5 ) );

Try using JSON.stringify as
$("#CXACNUM").val(JSON.sringify(Data5));

function BillerDetails() {
var iState = _xmlCFHttp.readyState;
var sStatus = "";
if (iState == 4) {
if (_xmlCFHttp.responseXML.xml != "") {
var $accNum = $("#CXACNUM");
var $accNme = $("#CXACNAM");
_xmlCFRecv.loadXML(_xmlCFHttp.responseXML.xml);
sStatus = _xmlCFRecv.selectSingleNode("/result/status").text;
if (sStatus == "1") {
if ($("#CXCLRCD option[value='" + $(this).children("Data1").text() + "']").length == 0) {
var Data4Val=$(this).children("Data4").text();
var Data5Val=$(this).children("Data5").text();
$("#CXACNUM").val($("#CXACNUM").val(Data5Val));
$("#CXACNAM").val($("#CXACNAM").val(Data4Val));
}
} else {
var msg = _xmlCFRecv.selectSingleNode("/result/message").text;
if (msg != "") {
alert(msg);
}
}
}
}
}
i have updated your code. hope this will work

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?

SAPUI5 Filter OData model based on fields using formatter

I have a List that contains ObjectListItems with content provided by an OData service. One of this contents is the title and the property has the value as follows:
title="{ path: 'title', formatter: 'app.schedule.util.Formatter.titleText'}"
As you can see there is a formatter in this title. The OData will bring a value like "available" or "disabled" and the formatter will transform it on the text for the specific language of the user.
I'm implementing a search capability on this List and it works fine, the problem is that it searchs only on the "available" and "disabled" values, and not in the formatted texts as it would be expected as this are not the values recognized by the user.
The filter code is:
handleSearch : function (evt) {
// create model filter
var filters = [];
var query = evt.getParameter("query");
if (query && query.length > 0) {
filters.push(new sap.ui.model.Filter("booked", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("weekday", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("title", sap.ui.model.FilterOperator.Contains, query));
filters = new sap.ui.model.Filter(filters, false);
}
// update list binding
var list = this.getView().byId("list");
var binding = list.getBinding("items");
binding.filter(filters);
},
Any idea on how to consider the formatter on the filter and not only the raw data?
Solution Considering you are doing only client side search:
Assumption: if you have grouping in the list..
handleSearch : function (evt) {
sFilterPattern = evt.getParameter("query");
sFilterPattern = sFilterPattern.toLowerCase();
var aListItems = this.getView().byId("list").getItems();
var bVisibility;
var oGroupItem = null;
var iCountInGroup = 0;
for (var i = 0; i < aListItems.length; i++) {
if (aListItems[i] instanceof sap.m.GroupHeaderListItem) {
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
oGroupItem = aListItems[i];
iCountInGroup = 0;
} else {
bVisibility = this.applySearchPatternToListItem(aListItems[i], sFilterPattern);
aListItems[i].setVisible(bVisibility);
if (bVisibility) {
iCountInGroup++;
}
}
}
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
}
applySearchPatternToListItem:function(oItem, sFilterPattern) {
if (sFilterPattern == "") {
return true;
}
//uncomment to search in oModel data
/*var oIteshellata = oItem.getBindingContext(this.sModelName).getProperty();
for (var sKey in oIteshellata) {
var sValue = oIteshellata[sKey];
// if (sValue instanceof Date) {
// //just for the filter take each number as string
// sValue = sValue.getDate() + "." +
// sValue.getMonth() + "." + sValue.getFullYear();
// }
if (typeof sValue == "string") {
if (sValue.toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
}*/
// if nothing found in unformatted data, check UI elements
if ((oItem.getIntro() && oItem.getIntro().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getTitle() && oItem.getTitle().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumber() && oItem.getNumber().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumberUnit() && oItem.getNumberUnit().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getFirstStatus() && oItem.getFirstStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getSecondStatus() && oItem.getSecondStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)) {
return true;
}
// last source is attribute array
var aAttributes = oItem.getAttributes();
for (var j = 0; j < aAttributes.length; j++) {
if (aAttributes[j].getText().toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
return false;
}

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

jquery error TypeError: Value not an object. with .split(',')

i am getting a strange error
Error: TypeError: Value not an object.
Source File: /Scripts/jquery-1.8.3.js
Line: 4
while i am trying to do a .split() with javascript.
Following is the snippet :
$("#item_qty_1").on("keydown", function (event) {
if (event.which == 13) {
var weight_code = $("#weight_code").val();
var qty = Number($(this).val());
if((weight_code == "2" || weight_code == "3") && qty <= 50)
{
var qty_sub_val = document.getElementById('item_qty_sub').value;
var qty_sub = "";
console.log(typeof qty_sub_val);
if(qty_sub_val != "" && qty_sub_val !== null)
{
qty_sub = qty_sub_val.split(',');
}
$("#test").html(qty_sub);
for(var i=1; i<=50; i++)
{
if(i>qty)
{
$("#qty_" + i).attr("tabindex","-1").attr("readonly","readonly").removeAttr("last").css("background","#e6e6e6");
}
else
{
if(qty_sub_val != "")
{
$("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white").val(qty_sub[i-1]);
}
else
{
$("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white");
}
}
}
$("#qty_" + qty).attr("last","0");
$("#unit1_list").modal();
}
event.preventDefault();
return false;
}
});
it is giving error only when qty_sub_val != ""; i.e. when .split(',') is called.
Please check what $("#item_qty_sub") returns. I think it is not returning the right value.

Browser freezing for a couple of second

When the following codes are running, it makes the browser freeze for a couple of secondes.
How could i prevent that ? Thanks
function rsfp_changePage(formId, page, totalPages, validate)
{
if (validate)
{
var form = rsfp_getForm(formId);
if (!ajaxValidation(form, page))
return false;
}
for (var i=0; i<=totalPages; i++)
{
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage)
document.getElementById('rsform_' + formId + '_page_' + i).style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage)
{
thePage.style.display = '';
try {
eval('if (typeof rsfp_showProgress_' + formId + ' == "function") rsfp_showProgress_' + formId + '(' + page + ')');
}
catch (err) { }
}
}
...
You will find the form on http://www.ocsl.ch/dev
username : stackoverflow /
password : stackoverflow
Login first and then go to http://www.ocsl.ch/dev/sejour-linguistique/adultes/demande-d-offre-en-ligne
Once on this page, click on the green button "suivant" and you will see that it freezes for a very little will.
Below the content form the script.js file which contain the ajaxvalidation fonction.
Hope that helps a bit. Please ask if you need any thing else that may help.
function refreshCaptcha(componentId, captchaPath)
{
if(!captchaPath) captchaPath = 'index.php?option=com_rsform&task=captcha&componentId=' + componentId;
document.getElementById('captcha' + componentId).src = captchaPath + '&' + Math.random();
document.getElementById('captchaTxt' + componentId).value='';
document.getElementById('captchaTxt' + componentId).focus();
}
function number_format(number, decimals, dec_point, thousands_sep)
{
var n = number, prec = decimals;
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
var abs = Math.abs(n).toFixed(prec);
var _, i;
if (abs >= 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec);
} else {
s = s.replace('.', dec);
}
return s;
}
function buildXmlHttp()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
function ajaxValidation(form, page)
{
try
{
var el = form.elements.length;
}
catch (err)
{
form = this;
}
var xmlHttp = buildXmlHttp();
var url = 'index.php?option=com_rsform&task=ajaxValidate';
if (page)
url += '&page=' + page;
var params = new Array();
var submits = new Array();
var success = false;
var formId = 0;
for (i=0; i<form.elements.length; i++)
{
// don't send an empty value
if (!form.elements[i].name) continue;
if (form.elements[i].name.length == 0) continue;
// check if the checkbox is checked
if (form.elements[i].type == 'checkbox' && form.elements[i].checked == false) continue;
// check if the radio is selected
if (form.elements[i].type == 'radio' && form.elements[i].checked == false) continue;
if (form.elements[i].type == 'submit')
{
submits.push(form.elements[i]);
form.elements[i].disabled = true;
}
// check if form is a dropdown with multiple selections
if (form.elements[i].type == 'select-multiple')
{
for (var j=0; j<form.elements[i].options.length; j++)
if (form.elements[i].options[j].selected)
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].options[j].value));
continue;
}
if (form.elements[i].name == 'form[formId]')
formId = form.elements[i].value;
params.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value));
}
params = params.join('&');
xmlHttp.open("POST", url, false);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
var success = true;
if (xmlHttp.responseText.indexOf("\n") != -1)
{
var response = xmlHttp.responseText.split("\n");
// All spans set to no error
var ids = response[0].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
document.getElementById('component'+ids[i]).className = 'formNoError';
// Show errors
var ids = response[1].split(',');
for (var i=0; i<ids.length; i++)
if (!isNaN(parseInt(ids[i])) && document.getElementById('component'+ids[i]))
{
document.getElementById('component'+ids[i]).className = 'formError';
success = false;
}
if (response.length == 4)
{
page = parseInt(response[2]) - 1;
totalPages = parseInt(response[3]);
rsfp_changePage(formId, page, totalPages, false);
}
for (var i=0; i<submits.length; i++)
submits[i].disabled = false;
}
if (success == false && document.getElementById('rsform_error_' + formId))
{
try {
document.getElementById('rsform_error_' + formId).style.display = '';
}
catch (err) { }
}
return success;
}
function rsfp_addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
function rsfp_getForm(formId)
{
var formIds = document.getElementsByName('form[formId]');
for (var i=0; i<formIds.length; i++)
{
if (parseInt(formIds[i].value) != parseInt(formId))
continue;
var form = formIds[i].parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
while (form.parentNode)
{
form = form.parentNode;
if (form.tagName == 'FORM' || form.nodeName == 'FORM')
return form;
}
}
}
Thanks #JuanMendes, it didn't help unfortunately. I made some reaserch to find out how could I modify the codes to send an asynchronous request but I didn't succeed. In the ajaxValidation fonction, there is
xmlHttp.open("POST", url, false);
if I change it to
xmlHttp.open("POST", url, true);
it should then be an asynchronous request, isn't it.
When I tested it, it didn't freeze the browser, however it doesn't show the error if fields are not filled up on the form. Instead, it validates which is not mean to be. Any help ?
As IAbstractDownvoteFactory mentioned, you're probably calling ajax in synchronous mode, which means exactly that, freeze the screen while you're waiting for the network call.
The reason it looks that way is that your ajaxValidation is returning a value. Typically, you would send an asynchronous request and your ajaxValidation would take a callback. Then the UI won't hang waiting for the XHR.
// This is an improvement over what you had
// Still poor code, since it's hard to tell what the function is doing
function rsfp_changePage(formId, page, totalPages, validate)
{
var form = rsfp_getForm(formId);
if (validate) {
// Change your AJAX validation function to take a callback, which passes the return
// value (asynchronous) instead of relying on a return value (synchronous)
ajaxValidation(form, page, function(validationResult){
if (validationResult) {
showProgress();
}
});
} else {
showProgress();
}
function showProgress() {
for (var i=0; i<=totalPages; i++) {
var thePage = document.getElementById('rsform_' + formId + '_page_' + i);
if (thePage) {
thePage .style.display = 'none';
}
var thePage = document.getElementById('rsform_' + formId + '_page_' + page);
if (thePage) {
thePage.style.display = '';
// Don't use eval, use window and bracket to avoid it
var func = window["rsfp_showProgress_" + formId];
if (typeof func == "function") {
func(page);
}
}
}
}
}

Categories

Resources