0

I was going through my book and found a piece of code which does not uses the traditional getElement method for selection but there is some shorthand used. Can some tell me more about this thing I know nothing of it frm.txt.value.

function  show_temp(){
    var Tval=frm.txt.value;
    alert("The temp in far. is " + Tval + " degree");
}
<form name="frm">
  Enter the temp in Fahrenheit:
  <input type="text" name="txt">
  <input type="button" value="temperature" onclick="show_temp()">
</form>
mx0
  • 6,445
  • 12
  • 49
  • 54
  • 1
    How old is that book? – j08691 Apr 02 '19 at 16:57
  • 1
    There's a great, thorough explanation in section 15.9.1 Selecting Forms and Form Elements in JavaScript: The Definitive Guide. See also https://developer.mozilla.org/en-US/docs/Web/API/Document/forms – j08691 Apr 02 '19 at 17:06
  • Dont know it's just a part of my school curriculum so I have to study it non the less examiners here arent a fan for some new or different method. Of writting the code – aditya prakash Apr 02 '19 at 18:57

1 Answers1

1

The shorthand you are referring to relates to the name attribute of the form and the input - this can be used to reference elements in JavaScript and can be used as an alternative to getElementById etc.

    function  show_temp(){
             console.log(frm.txt);
         }
    <form name="frm">
            Enter the temp in Fahrenheit:
            <input type="text" name="txt">
            <input type="button" value="temperature" onclick="show_temp()">
        </form>

However, it is not recommended - unlike an id, a name attribute can be repeated throughout the page, so referencing frm.txt in this 2nd snippet below would actually return an array of results rather than a single result (click the temperature button on both for a comparison).

    function  show_temp(){
             console.log(frm.txt);
         }
    <form name="frm">
            Enter the temp in Fahrenheit:
            <input type="text" name="txt">
            <input type="text" name="txt">
            <input type="button" value="temperature" onclick="show_temp()">
        </form>
DKyleo
  • 806
  • 8
  • 11