2

I have an input field in HTML:

<input type="text" id="id-name">

I'm generating a random value here:

function rand(length, current) {
    current = current || '';
    return length ? rand(--length, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".charAt(Math.floor(Math.random() * 60)) + current) : current;
}

and I've defined an empty array:

var sample = sample || [];

After calling the rand() function, I'm trying to push the randomly generated value into the array, along with two other object properties and values:

(function() {
    $("#id-name").val(rand(5));
    var value = $("#id-name").val();
    sample.push({acct:"sample-code", labels:"sample label", trackingcode: value});
})();

I can't get the push method to insert the data into the 'sample' array. I've already tried referencing this topic, but wasn't able to figure out what I'm doing wrong. I don't think it's pushing correctly because when I run:

alert(sample);

all I get is [object Object]

Here's a jsFiddle link to test things out.

Community
  • 1
  • 1
Mike T.
  • 21
  • 1
  • 4
  • 1
    What makes you think it's not working? – Pointy Apr 02 '13 at 22:18
  • You're probably running your code before the DOM is ready, so the `id-name` element doesn't exist yet. Or you're doing something asynchronous. Not enough info in the question, but your `.push()` code is correct. –  Apr 02 '13 at 22:18
  • works for me -> [**FIDDLE**](http://jsfiddle.net/nA8B4/) (PS: jsFiddle waits for DOM ready) ? – adeneo Apr 02 '13 at 22:25
  • Edited above to give more context. adeneo, I checked console and all I got was [object Object]. Is that functioning as expected in jsFiddle? – Mike T. Apr 02 '13 at 22:30
  • Don't alert, use console.log and you'll see the real thing. – bfavaretto Apr 02 '13 at 22:34
  • The fiddle you provided looks just fine to me. https://dl.dropbox.com/u/67589325/Screenshots/1364942261.png – 000 Apr 02 '13 at 22:38
  • @adeneo Yeah, you have the default `window`'s `load` wrapper set in the top left of the fiddle. – Fabrício Matté Apr 02 '13 at 22:49
  • `[object Object]` is exactly what you should be getting, as alerts only outputs strings, not objects, you'll need to use the console for that, as noted by @bfavaretto above. – adeneo Apr 02 '13 at 22:51
  • You guys were right - thanks everyone for the quick feedback! I wasn't aware that alert only outputs strings. Still learning basic things like this everyday :) – Mike T. Apr 02 '13 at 23:38

0 Answers0