got confused with 'this' in one form in js - javascript

<HTML>
<HEAD>
<TITLE>Example 5.3</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function calculate(form) {
form.results.value = eval(form.entry.value);
}
function getExpression(form) {
form.entry.blur();
form.entry.value = prompt("Please enter a JavaScript mathematical expression","");
calculate(form);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM METHOD=POST>
Enter a JavaScript mathematical expression:
<INPUT TYPE=text NAME="entry" VALUE="" onFocus="getExpression(this.form);">
<BR>
The result of this expression is:
<INPUT TYPE=text NAME="results" VALUE="" onFocus="this.blur();">
</FORM>
</BODY>
</HTML>
Above code is from one js tutorial.
Question:
onFocus="getExpression(this.form);" , what does this represent here? I thought it is window object, if so, then can not explain this line: onFocus="this.blur();", or both this mean the input field, if so, how to userstand this.form(input.form)?
I got confused with 'this' here, could anyone explain to me? Thanks.

onFocus="getExpression(this.form);" , what does this represent here?
this here is your input <INPUT TYPE=text NAME="entry"/>
onFocus="this.blur();"
this here is your input <INPUT TYPE=text NAME="results"/>

this means it refers to that particular form, and that particular element.
Example: this is the Shortest answer I ever posted (Refers to this question)

The this keyword is a tricky one in the JS Environment I would recommend this article since it really helped me to understand it some time ago. Understanding the this keyword.
In this case if the function is not being executed by call() or apply() which modifies the behaviour of the this keyword it should represent the caller of the function, in this case the input that the event was triggered from.
Hope this helps :)

Related

Using <form> and <input> elements as an input for JavaScript code. Is this the best way to do this?

Folks,
I am newbie to coding, obviously, so having completed few Lynda courses recently on HTML and Javascript, I have hit a wall with my simple HTML page. Basically, what I want is to do a basic calculation with JavaScript to have the user enter the two numbers using HTML form/ input elements and do a basic arithmetic calculation on JS. For some reason the code is not working. Can somebody point me to the right direction as why those input values are not being read by JS? Is getElementById the correct way?
Also, I am using the console.log to dislpay the results as I don't know yet how to have it displayed on the HTML page as a text below the submit button.
The HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Accurate Mass Error Calculator</title>
</head>
<body>
<h1> Accurate Mass Error Calculator </h1>
<p> Please enter the values below for each field:</p>
<form onsubmit="return calculateError()" method="post">
<p> Exact Theoretical Mass: <input id="exactMass" type="number" step="any" name="exactMass"/></p>
<p> Accurate Experimental Mass: <input id="accurateMass" type="number" step="any" name="accurateMass"/></p>
<p> <input id="submitButton" type="submit" name="submit1" value="Calculate" onclick="return calculateError()" /></p>
</form>
<script type="text/javascript" src="ppmError.js"></script>
</body>
</html>
The JS code(ppmError.js):
function calculateError () {
var exactMass=document.getElementById("exactMass");
var accurateMass=document.getElementById("accurateMass");
var ppmError=(accurateMass.value-exactMass.value)/exactMass.value*1000000;
if (isNaN (ppmError) ) {
console.log ("Not a valid Entry! Please try again.")
} else {
console.log(ppmError);
}
}
As Satpal said in the comment you should indeed cast your text to an int with :
var exactMass = parseInt(document.getElementById("exactMass").value);
var accurateMass = parseInt(document.getElementById("accurateMass").value);
var ppmError=(accurateMass-exactMass)/exactMass*1000000;
For your other question, in your html add an empty paragraph where you want to display your result
<p id="result"></p>
And instead of calling console.log you can do :
document.getElementById('result').innerHTML = ppmError;
Use solution from singe31, but to prevent reloading of the page after click change type of your button from "submit" to "button" or place "return false;" as the last line of calculateError() function. Otherwise you won't see any change on the page.

Update HTML form with Javascript while typing

I can update an HTML form using Javascript, when the user hits enter when on something on the form or when he triggers the onclick event on the "submit" button, but I want the form to be updated while the user is typing something.
I know that I can do Infinity loop, yet it is not a good idea; or I can check after intervals but it will cause unnecessary checking, which I don't want.
Use keyUp event handler with the input field contained within your form.
References: Javascript,
jQuery
[UPDATE]
You missed round brackets at function definition, check the updated fiddle
I had the same question and based on this post and sohel's answer I managed to get it working. Now I would like to share my solution in form of a short working example: If you type your name in the first field it will suggest an email address in the second one.
<!DOCTYPE html>
<html>
<head>
<script>
function nameModify(emailElement, nameElement) {
emailElement.value = nameElement.value + '#stackoverflow.com';
}
</script>
</head>
<body>
<form name="aform" action="#">
<input type="text" name="name" onkeyup="nameModify(this.form.elements['email'], this);" >
<input type="text" name="email" >
</form>
</body>
</html>
You are looking for Autocomplete

Firefox will not validate form data

The following simple form with javascript with onclick button does not work in Firefox (I have version 7) but works fine in IE, Chrome, and Safari.
What am I missing?
<head>
<script type="text/javascript">
function result() {
alert(calc.input.value);
}
</script>
</head>
<body>
<form name="calc" action="">
<input class="cInput" type="text" name="input" size="16" /><br/>
<input type="button" class="cButton" name="seven" value="1" onclick="calc.input.value += '1'" />
<input type="button" class="cButton" name="equal" value="=" onclick="result()" /><br/>
</form>
</body>
<script type="text/javascript">
var calc;
function result() {
calc = document.forms['calc'];
alert(calc.input.value);
}
</script>
What am I missing?
You are missing that IE adds element names and ids as global variables. Some other browsers in certain conditions (sometimes requiring the document to be in quirks mode) will copy that habbit, some wont.
So in IE (and some others) the form name calc is a global variable referencing the form and in other browsers it isn't.
The method in Dunuyadnd's answer is a robust, cross-browser way to get a reference to the form. The formal access method is:
document.forms['calc'];
Named form controls can accessed similarly:
document.forms['calc'].elements['input'];
or
document.calc.input;
Be careful with giving controls names that are the same as tags, it is a bit confusing. Also, if there is more than one control with the same name, you will get an HTML collection rather than a single element.
You may want to read about HTMLForms and their related elements.

How do I highlight all invalid dijit.form.ValidationTextBoxes on a dijit.form.Form?

what I'm after is a form that when submitted, runs a validation check, and highlights all invalid fields and adds the tooltips.
I'm effectively looking for something like this:
dojo.forEach(dijit.byId('myForm')._invalidWidgets, function (thisWidget,index,array) {
thisWidget.displayMessage("normal invalid/empty message should go here, seems I should be calling something higher level than this");
});
but I don't want to be digging that deep, all I want to do is trigger the same sort of thing that's triggered when you tab out of an empty required field (exclamation icon and appropriate invalid/empty message). Maybe I should just try and fire the tab-out event?
Can someone point me in the right direction?
Yes, you're correct - you can get all your validation, highlighting, even focus on the first invalid field by just calling the validate() function on a dijit.form.Form element.
Here's an example where the validate() call is added to the onSubmit event:
<head>
<script type="text/javascript">
dojo.require("dojo.parser");
dojo.require("dojo.form.Form");
dojo.require("dojo.form.ValidationTextBox");
dojo.require("dojo.form.Button");
// more includes here...
</script>
</head>
<body>
<form dojoType="dijit.form.Form" action="..." method="...">
<input dojoType="dijit.form.ValidationTextBox" trim="true" regExp="..." invalidMessage="Oops...">
<!-- // more form elemts here... -->
<button type="submit" dojoType="dijit.form.Button" ...>
Submit
</button>
<script type="dojo/method" event="onSubmit">
if (!this.validate()) {
alert("Form contains invalid data. Please correct....");
return false;
}
return true;
<script>
</form>
</body>
Hope, you find it helpful.
Cheers.
Follow-up:
Here's an example of an input field that could be used to help prompt a user as to what sort of data is expected, and would alert them when validation fails:
<input type="text" id="EXT" name="EXT" value=""
maxLength="10"
dojoType="dijit.form.ValidationTextBox"
regExp="\d+?"
trim="true"
promptMessage="<p class='help'>Please your extension. (i.e. "1234")</p>"
invalidMessage="<p class='help'>The extension field should contain only numbers.</p>">
This is a declarative example. (I misspelled it in my initial response below.)
jthomas_ in #dojo on irc.freenode.net answered my question. It turns out that I wanted to be using dijit.byId('myForm').validate() which does everything I wanted in one swoop. Thanks, jthomas_!

How can I get IE's Javascript to implement the 'this' keyword functionality?

Is there a workaround for Internet Explorer to implement the functionality offered by 'this' javascript keyword to get the dom element that triggered the event?
My problem scenario is :
I have a variable number of text fields in the html form, like
<input type="text" id="11"/>
<input type="text" id="12"/>
..
I need to handle the "onchange" event for each text field, and the handling is dependent on the 'id' of the field that triggered the event.
So far I understand that my options are:
1) attach a dedicated event handler for each text field. so if I have n fields, i have n different functions, something like:
<input type="text" id="11" onchange="function11();"/>
<input type="text" id="12" onchange="function12();"/>
but the text fields are added and removed dynamically, so a better way would be to have one generic function instead.
2) use the 'this' keyword like:
<input type="text" id="11" onchange="functionGeneric(this);"/>
<input type="text" id="12" onchange="functionGeneric(this);"/>
But this option does not work with Internet Explorer.
Can anyone suggest a work around for getting it work in IE or some other solution that can be applied here?
Thanks.
I can't reproduce your problem. Here's an SSCCE based on the latest information in comments:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2618458</title>
<script>
function functionGeneric(id) {
alert(id); // Shows either 11 or 12 correctly.
}
</script>
</head>
<body>
<input type="text" id="text_11" onchange="functionGeneric(this.id.split('_')[1]);"/>
<input type="text" id="text_12" onchange="functionGeneric(this.id.split('_')[1]);"/>
</body>
</html>
It works fine in all major browsers I have here. Your actual problem lies somewhere else. Until you come up with more detail, or better, an SSCCE, it's shooting in the dark to the root cause.
The second option probably does not work because element IDs must start with alphabet or the underscore character (at least, according to the spec).
I would opt for something like this:
// make the ids start with a word, like "foo", followed by "_", followed by a number
$("input[id^='foo_']").change(function() {
doSomething(this.id.split("_")[1]); // extract the number, pass to function
});
That will attach a change handler to all of your inputs with IDs starting with 'foo', and split the number out of the ID to pass to the generic function which works on the number.

Categories