Javascript function not working with an array - javascript

i have this function which loops through an array of check boxes checking if the boxes value is equal to something in a text box, i dont know whats wrong.
function checkValue(contain) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].name == "vote[]") {
if (boxes[i].value.indexOf(contain.value) != -1) {
boxes[i].checked = true;
}
}
}
}
and this is how i call it
OnClick="uncheckAll(); checkValue(document.getElementsByName("countrylist"));"
this code is in side a echo in php which is like this echo ' ';

You cannot nest the same type of quotes in HTML.
OnClick="uncheckAll(); checkValue(document.getElementsByName(\'countrylist\'));"
Simply escape the single quotes as shown as PHP provides an easy escape mechanism.

the contain argument you're passing is an array not a string. that could be the problem?

I think your javascript might be having an issue with the name of your field being vote[].
Does it ever pass the condition:
if (boxes[i].name == "vote[]") {

1) Update the inlince call to use single quotes:
checkValue(document.getElementsByName('countrylist'))
2) Use document.getElementsByName to make the function little better:
function checkValue(contain)
{
var boxes = document.getElementsByName("vote[]");
for (var i = 0; i < boxes.length; i++)
{
boxes[i].checked = (boxes[i].value == contain.value);
}
}

Related

javascript get only array elements equal to variable

I'm trying to compare the variable determineHour against the array stationRentalsHours, whenever the variable would be equal to a stationRentalsHours element, I'd like to add that element to another Array (stationRentalsHoursTemp), but only the values that match. I tried with simple operators, but that doesn't put anything into the temp array. I also tried using JQuery $.inArray, but that gives me some strange results, Equal to those in the original array. Are there any other methods of comparing a variable with an array for this particular task?
Thank you for any help.
function updateChart() {
if(canvas3){canvas3.destroy();}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
/*if(determineHour == stationRentalsHours){
stationRentalsHoursTemp.push(stationRentalsHours[i]);*/
if( $.inArray(determineHour, stationRentalsHours[i])){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
In this case, instead of using $.inArray, you can simply use the for loop and the index to test the equality. I guess you mixed up two things:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++) {
if( determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
Better yet, use filter:
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
stationRentalsHoursTemp = stationRentalsHours.filter(function(val){return val == determineHour;});
Instead of
if( $.inArray(determineHour, stationRentalsHours[i])){
Try
if( $.inArray(determineHour, stationRentalsHours) != -1){
Your commented out code would do the trick with a slight amendment to the if condition. Your original condition was comparing a string to an array instead of an individual element in that array:
function updateChart() {
if(canvas3){
canvas3.destroy();
}
var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
for (var i = 0; i < stationRentalsHours.length; i++){
if(determineHour == stationRentalsHours[i]){
stationRentalsHoursTemp.push(stationRentalsHours[i]);
}
}
}

Using for loop to find specific characters in string

I am attempting the bean counting example in the functions chapter of the book Eloquent Javascript. My function is returning a blank.
Without giving me the full answer (I'm working through this example to learn), can someone tell me why my code is not printing any text?"
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++);
function getB(){
if (string.charAt(i) == "b")
return i;
else return "";
}
console.log(getB());
There is something wrong about how you're trying to implement this feature.
First of all I think it's better if you have a function that accepts the string and the char as parameters in order to call it whenever you want.
Example of calling :
getChar('this is my custom string', 'c') -> it should search character `c` in `this is my custom string`
getChar('this is another custom string', 'b') -> it should search character `b` in `this is another custom string`
Example of implementation :
var getChar = function(string, char){
for(var i=0;i<string.length;i++)
{
if(string.charAt(i)==char) console.log(i);
}
}
Now, try to make it not case-sensitive and instead of console.log the output try to return a sorted array with character positions
Use This,
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++) {
if (string.charAt(i) == "b") {
console.log(i);
}
}
if you want to print every position your value is at, you can program something like this:
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++)
{
getChar(i, "b");
}
function getChar(i, input)
{
if (string.charAt(i) == input)
console.log(i);
}
another example: collect all b positions:
var string = "donkey puke on me boot thar be thar be!";
function getB(string){
var placesOfB = [];
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "b") {
placesOfB.push(i);
}
}
return placesOfB;
}
console.log(getB(string));
tip: your for has no body (putting ; after it just loops without doing anything)...
and it does not make sense to define a function inside that for.
Without giving you the full answer, I'll just give you pointers:
1. Your for loop is not complete - it doesn't do anything.
2. Your getB() function needs to accept string parameter in order to perform some action on it.
3. The if..else statement doesn't have opening and closing brackets {}

Javascript function not getting a value from an input box and loop through an array

im trying to gather an amount from a input box and then tick a certain amount of boxes which is an array.
this is what i got so far and it doesnt work :S
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < ting.value; i++) {
if (boxes[i].name == "vote[]") {
boxes[i].checked = true;
}
}
}
And im calling it with this:
uncheckAll();
checkAmount(document.getElementsByName(\'ammount\'));
getElementsByName returns an array and your function is expecting a single element, you need to access the first element like this:
checkAmount(document.getElementsByName(\'ammount\')[0]);
Change the ting.value to boxes.length in the for loop:
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
boxes[i].checked = (boxes[i].name == "vote[]") ;
}
}
Try this:
boxes.item(i).checked = checked
sorry not sure how to insert javascript into the post
are you posting your real code?
If so, you realize that you are spelling 'amount' wrong in your function call?
From your statement "gather an amount from an input box" I think you expect ting to be a number entered into a text box and so you are calling a function that expects a number with a value that should resolve to an array of form element objects?
var m = document.getElementsByName("amount");
m will be an array!
in other words, it might work better if you made sure you were passing a number when you call checkAmount:
checkAmount(documents.forms[0].amount.value)
or:
checkAmount(documents.getElementsByName("amount")[0].value)
It would help a lot if you post the actual HTML and actual javascript code.
There are several problems with the code you posted, as indicated by the previous answers and replies. Try something like this:
function checkAmount(ting) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < ting.value && i < boxes.length; i++) {
if (boxes[i].name == "vote[]") {
boxes[i].checked = true;
}
}
}
Called like this:
uncheckAll();
checkAmount(document.getElementsByName(\'ammount\')[0]);
Now you are safe from array out of bounds errors no matter the value typed in the input field and the call to checkAmount should work.
Try using
checked=checked
instead of
checked=true

find a href with a certain value

I have an array called "selectMe" formed by a variable wich contains a string such as: 12P, 5B, 10C, etc., this is the "href" value of a hyperlink and I need to find and add the class "selected" to the ones inside this array. To break the array I have:
function selectPrevious(selections){
// split into array
var selectMe = selections.split(", ")
for (var i = 0; i < selectMe.length; i++){
$('#theater a').search(selectMe[i]).addClass('selected');
}
}
I've tried doing find() instead of search() as well as many other iterations but still haven't been able to accomplish what I want, how can I do it?
EDIT
Using one of the answers provided here I have changed it to this:
function selectPrevious(selections){
// split into array
if(typeof selections !== "undefined"){
var selectMe = selections.split(", ");
for (var i = 0; i < selectMe.length; i++){
$('#theater a[href*='+selectMe[i]+']').addClass('selected');
}
}
}
I had to add the "if(typeof selections !== "undefined")" because otherwise it was throwing me errors on IE. Anyway, I still can't add the class "selected" to the values in the array, am I missing something? or did I do something wrong?
Your selector for find() is wrong. And there are no search() in jQuery.
Instead of $('#theater a').search(selectMe[i]) use $('#theater a[href*='+selectMe[i]+']')
try this one:
function selectPrevious(selections) {
// split into array
var selectMe = selections.split(", ")
for (var i = 0; i < selectMe.length; i++){
$('#theater').find('a[href*='+selectMe[i]+']').addClass('selected');
}
}

How to pass the html name of button group to a javascript function

Say I have a function similar to this:
function getGroupValue(group)
{
for (var i=0; i < group.length; i++)
{
if (group[i].checked)
{
return group[i].value;
}
}
}
that i can call with something like getGroupValue(document.forms[0].myGroup)
How do I convert this to just passing in the name of a html radio button group like
getGroupValue('myGroupName') ?
This should work:
function getGroupValue(group)
{
var g = document.getElementsByName(group);
for (var i=0; i < g.length; i++)
{
if (g[i].checked)
{
return g[i].value;
}
}
}
I'm assuming there's only one form on your page, given the way you were originally calling the function. If that's a valid assumption to make, then you can do the following:
function getGroupValue(groupName)
{
var group = document.forms[0][groupName];
for (var i = 0, n = group.length; i < n; i ++)
{
if (group[i].checked)
{
return group[i].value;
}
}
}
Javascript lets you specify attributes/children of the form using the brackets, so you can just use the groupName you passed in as a child of the form itself.
It's easier to give all the radio buttons a common "group" class name, and use a CSS selector (jQuery, Prototype), then loop through the returned results and grab the name for each.
You could do a document.getElementsByName([GroupName]) and get the collection that way. If there are multiple groups, you can store the group name in a variable and have it pass just as you are doing now.

Categories

Resources