Nico84468
Nico84468

Reputation: 23

jQuery - Access form items through function

I found on some examples on the web that people were passing the form to a function and then they were only using the id of the item to access it like in :

<form id="frm">
<input type="text" id="textbox" name="textbox" value="some value" />
</form>

<script>
console.log(getelementval("#frm"));

function getelementval(frm) {
return frm.textbox.val();
}
</script>

But FireBug tells me that frm.textbox is undefined... Then I'm searching why it doesn't work on the net but I didn't find anything explaining this option and how to use it. Any clues?

Upvotes: 2

Views: 203

Answers (2)

Blender
Blender

Reputation: 298582

You will have to modify the JS slightly to make this work:

function getelementval(frm) {
    return $(frm)[0].textbox.value;
}

Demo: http://jsfiddle.net/gdZEK/2/

  • $(frm) returns an element matching the selector.
  • [0] fetches the actual DOM element.
  • .textbox works on DOM elements only, not jQuery objects. It matches [name='textbox'].
  • .value needs to be used instead of .val(), as .textbox isn't a jQuery object.

Honestly, I don't really see how this is better than just using jQuery:

$('#frm input[name="textbox"]').val();

Upvotes: 3

codingbiz
codingbiz

Reputation: 26406

This is pure JavaScript and not JQuery

function getelementval(frm) {
   var f = document.getElementById(frm);
   return f.textbox.value;
}

console.log(getelementval("frm"));

JQuery version

function getelementval(frm) {
   var f = $(frm)[0];
   return f.textbox.value;
}

console.log(getelementval("#frm"));

Upvotes: 1

Related Questions