Geo
Geo

Reputation: 3200

variable.length is undefined when length = 1

I am using js to alert the length of a variable(field) but is crushing when my field.length is supposed to be equal to 1.

When field.length is greater than 1 everything works fine. Any ideas?

This is the HTML code

<form>
<someloop>
<input class="checkbox" type="checkbox" name="mark" value="#recID#">
</someloop>
<button class="btn btn-danger" type="button" onClick="dlte(mark);" >Delete</button>
</form>

JS Code:

function dlte(field){
        alert(field.length);
    }

Upvotes: 0

Views: 348

Answers (3)

Geo
Geo

Reputation: 3200

This is the solution I found for my issue

function(filed){
 'var $srt = $(field); 
  alert($srt.length);' 
}

Also, a note to @DaHaka and @Steve H.

You recommended that I had to add single quotes around my varibale ('mark') but this ended up braking my code for some reason. When I took them off the code started working as I wanted it. Regardless of that, thanks for the help and recommendations!! :)

Upvotes: 0

Steve H.
Steve H.

Reputation: 6947

You cannot pass references of DOM nodes as you are attempting in your onClick handler.

Try:

onclick="dlte('mark');"

and the function:

function dlte(field) {
    var nodes= document.getElementsByName(field);
    alert(nodes[0].length);
}

Upvotes: 3

nanobash
nanobash

Reputation: 5500

<button class="btn btn-danger" type="button" onclick="dlte('mark')" >Delete</button>    

function dlte(field){
    alert(document.getElementsByName(field).length);
}

If your mark name is name of html element you should use getElementsByName property to get length

Upvotes: 2

Related Questions