I'm using the jQuery library, and attempting to push items to an array:
< onclick ="setFacet('myarray','val');">AOC
var myarray = [];
function setFacet(arr, bb) {
for (var i=0; i< arr.length; i++)
if (arr[i] == bb)
return true;
arr.push(bb);
return false;
}
I get this in chrome:
Object myarray has no method 'push'
4 Answers 4
Oh, I think I found the issue. In your onclick, you're calling the function with two strings. The first argument should be an array rather than 'myarray'.
If you just get rid of the quotes (and if myArray is in the global scope) it should work. That is, have it look like this:
onclick="setFacet(myArray, 'val')"
2 Comments
myArray is a global variable, you should be able to just do onclick="setFacet(myArray, 'val')".Change:
onclick="setFacet('myarray','val')"
To:
onclick="setFacet(myarray)"
then change the function setFacet to the following:
function setFacet(arr, bb) {
for (var i=0; i< arr.length; i++)
if (arr[i] == bb) return true;
arr.push(this.innerHTML); /* "this" in the context of the "click" */
/* is the element clicked */
return false;
}
Comments
the element with the onclick listener should be
<...onclick ="setFacet(myarray,'val');">
myarray should not be quoted, otherwise it will be treated as a string.
Comments
You could separate your javascript from your markup altogether and just store the value as an attribute of the clicked element (or any other element)
<input type="button" value="someValue">
<script>
$(function(){
var myArray = [];
$('#myEle').click(function(){
myArray.push($(this).val())
})
})
</script>
myarrayand notarr?