2

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?

1
  • Why would you use this ugliness if you have jQuery? Commented Oct 20, 2012 at 0:18

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

@bažmegakapa agreed. +1-able even without :-) see the revisons :-)
1

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"));

2 Comments

this is not the normal way to do it with jQuery, but the vanillaJS method is good for reference
the JQuery stuff could get messy - I just wanted to keep it simple and clear

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.