PDA

View Full Version : if serialize(s) returns empty, show: 0



Null
07-13-2008, 08:05 PM
I have the following function:


function serialize(s)
{
serial = $.SortSerialize(s);
document.getElementById('serial').value=serial.hash.replace(/sort3\ [\]=/gi, '').replace(/&/g, ',');
};

This returns a string like: 1,2,4,6,8

It is possible that there is nothing to sortserialze, so it returns
nothing. When this is the case, I want it to return a "0" instead of " ", but how to do this?

So if there is nothing to serialze return: 0

Thanks

jscheuer1
07-14-2008, 03:22 AM
There is no return value to that function (so it will always return undefined), but I think you mean the value it sets for the element. If so, this should work out fine:


function serialize(s){
var serial = $.SortSerialize(s),
tmp = serial.hash.replace(/sort3\ [\]=/gi, '').replace(/&/g, ',');
document.getElementById('serial').value = tmp == '' || tmp == ' '? '0' : tmp;
};

Notes If I knew more about just what this was doing, I might try to set it up so that, if there were some type of input error, that would be caught and dealt with somehow and/or use a RegExp (instead of string equality) to test tmp. You had an undeclared global variable (serial) in your version. I've corrected that, but if it was already declared in the global scope and needs to remain like that for the rest of your code, use:


function serialize(s){
serial = $.SortSerialize(s);
var tmp = serial.hash.replace(/sort3\ [\]=/gi, '').replace(/&/g, ',');
document.getElementById('serial').value = tmp == '' || tmp == ' '? '0' : tmp;
};

Null
07-14-2008, 08:52 AM
Hi,

Thanks for the reply, but both codes don't work :(.

I've set op a demo page. When pressing the update button it wil "index" the right column. If you drag all items out of it and then press update, the textfield will stay blank (the colum is empty). In that case I want it to display a 0. Since the sortserialize makes this indexing happen, I though it has to display the 0 aswell...

The url:
http://www.sourceskins.com/sort.html

Thanks

jscheuer1
07-14-2008, 03:51 PM
I had copied a typo from your original post in this thread. This works:


function serialize(s)
{
var serial = $.SortSerialize(s),
tmp = serial.hash.replace(/sort3\[\]=/gi, '').replace(/&/g, ',');
document.getElementById('serial').value = tmp == '' || tmp == ' '? '0' : tmp;
};

You had placed a space in the regular expression, which is not there on your page:



/sort3\ [\]=/gi

That changed its meaning completely and (at least in FF 3, for some reason) invalidated the entire page. Ordinarily, I would have thought it would only have produced a script error, or maybe even just an unexpected output. In any case, my first solution would have worked had your code been presented properly in your first post.

Null
07-15-2008, 03:46 PM
A thank you very much, it works great now! Funny how a single space can mess things up entirely :)

Thanks again!