tags:

views:

53

answers:

3
<a href="javascript:SelectAll(this.form)">All </a>
<input type ="button" value ="test" onClick="SelectAll(this.form);" />


    <script ......>
    function SelectAll(form)
    {
        alert(form); 
    }
    </script>

method 1 produce an alert message 'undefined' while 2 method works fine by displaying form object . I'm very much aware that anchor elements don't have a form property, that references the form , unlike input elements,but is there any alternative way to pass form object using hyperlink or is there any way to style the button to look like an hyperlink

Thanks

A: 

Since the anchor is not a form control, it doesn't have a form property. You would need to find some other way to reference the form (or stick to a button, which is the right choice of control for something like this).

David Dorward
+1  A: 

Try this...

onClick="SelectAll(getParentForm(this));"

function getParentForm(el) {
  while(el = el.parentNode) {
    if(el.tagName.toLowerCase() === "form")
      return el;
  }

  return null;
}
Josh Stodola
A: 

Honestly? I think your best approach is to not use an anchor element at all. It's not really a link, so that's actually a misuse of HTML.

Use a button element instead, which does have a form property. If you really want it to look like a link, slap on a little CSS to make it look like one.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
button.link {
  border: none;
  background-color: transparent;
  color: blue;
  margin: 0;
  padding: 0;
  cursor: pointer;
  text-decoration: underline;
}
</style>
<script type="text/javascript">

function SelectAll( f )
{
  alert( f );
}

</script>

</head>
<body>
  <form id="test">
    <button class="link" onclick="SelectAll(this.form)">All</button>
  </form>
</body>

But there are probably a dozen other ways to get a reference to the form element itself. If your form definition looked like this

<form id="test" name="tester">

and it's the only form on the page, here are some ways to obtain a reference to it

document.forms.tester
document.forms['tester']
document.forms[0]
document.getElementById( 'test' )
Peter Bailey
You should validate that HTML.
David Dorward
Uhhh, why? it's just an example - I think it's extremely silly to validate every little snippet of HTML. Ok, so I forgot the `</html>` and the `<button>` should be in another block element - big deal. It gets the point across without being 100% valid markup.
Peter Bailey