Passing execution context in JavaScript from html elements - javascript

I am very new to JavaScript programming, and i am trying to do form validation using JavaScript.
While learning form validation i was reading about how to disable submit button until all input fields are validated, i saw many techniques to do this, but, i am confused regarding the following code:
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage(this)" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var bt = document.getElementById('btSubmit');
if (txt.value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>
Here this is passed as an argument from an input element event listener in html. I tried passing something other than this from there, it didn't work only passing this works,
As far as i know this in JavaScript signifies current-execution-context, but since this is JavaScript keyword then how it is interpreted inside html?
JS FIDDLE LINK while passing 'this': https://jsfiddle.net/s0vnjpqb/
JS FIDDLE LINK while passing 'some': https://jsfiddle.net/s0vnjpqb/
PS: I am new to JavaScript, hence the question is easy, this might not match the standards of stack-overflow, but i tried researching in stack-overflow as well as on other platform i couldn't understand it.

As you mentioned correctly in the description that this in Javascript signifies the current execution context.
Similarly in html
this also represent the value of the ThisBinding of the current execution context and this.value indicates the value of the current execution context
e.g txt.value in your case.
Alternately what you can do is,
<body>
<h3>Enter some values in the text to enable the button!</h3>
<input type="text" id="txt" onkeyup="manage()" /> //focus here on "this" parameter
<input type="submit" id="btSubmit" disabled />
</body>
<script>
function manage(txt) {
var value = document.getElementById("txt").value;
var bt = document.getElementById('btSubmit');
if (value != '') {
bt.disabled = false;
}
else {
bt.disabled = true;
}
}
</script>

Related

Changing a Value on Key Up

This may be a simple JavaScript problem, but I really don't know what's wrong with my code.
What I would want to do is very simple, there is an input element in my template, and I would like to change the value of it whenever there is a key up.
The following is the relevant part of my code.
var track = document.getElementById("id_tracking");
track.value = "a";
function track_record() {
track.value = "b";
}
$(document).ready(function() {
$("#id_urnA_red").keyup(function() {
c_urn();
react();
track_record();
});
$("#id_urnA_blue").keyup(function() {
c_urn();
react();
track_record();
});
});
function c_urn() {}
function react() {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="id_urnA_red" />
<input id="id_urnA_blue" />
<br><br>
<input type="text" name="tracking" id="id_tracking" />
Here, id_urnA_red is an input element. When its value changes, I would like the value of id_tracking to change.
Other functions c_urn and react are implemented normally on key up. I am confused why track_record is not implemented.
Thank you

forcing focus to remain on a form text element until the value is numeric

I have a form which has input fields that expect numbers only.
I'm using javascript to validate the form when the value of the field changes.
If the value is numeric, do nothing.
If the value is not numeric, set it to zero and put focus in that text field. Essentially, I'm trying to trap the cursor in that field until a numeric value is entered. For some unknown reason, focus is not being placed on that form element. cell.focus() does not work. I've even tried document.getElementById(cel.getAttribute("ID")).focus(); What might I be doing wrong?
<html>
<head>
<script>
function NAN(cell){
if (cell.value != "") {
var re = /^(0|[1-9][0-9]*)$/;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = "0";
cell.focus();
}
}
}
</script>
</head>
<body>
<input type="text" name="num" value="" onchange="NAN(cell)"/>
</body>
</html>
Your problem is in the onchange attribute:
<input type="text" name="num" value="" onchange="NAN(cell)"/>
The value is executed as JavaScript code directly. You're passing code, not just a generic signature or prototype.
Inside those event handler snippets, there's a special object this defined, referring to the current DOM element (the input tag in this example).
(Just to mention it, there is also a second predefined object event, which most likely caused your confusion.)
As a simple fix for your issue, replace cell with this in the call and it should work:
<input type="text" name="num" value="" onchange="NAN(this)"/>
It's also important to note that you should keep in mind that this verification requires JavaScript to be executed. If it's disabled, the user might still pass any values, so you should check the value server side as well (assuming this isn't just client-only code).
As an alternative to using JavaScript, you could just use HTML5 to force a specific pattern on inputs. In this case this would be trivial to do:
<input type="text" name="num" value="" pattern="(?!0)\d+" title="Quantity">
The user won't be able to submit the form unless the pattern is validated, so there's no need to force the input focus. The pattern always has to match the full value, from beginning to the end. The title attribute is typically used to provide more information in the error popup.
There are two things done:
You have to change cell to this with onchange.
According to this question at least with Firefox setTimeout has to wrap this focus-method so that it works as expected.
And a more user-friendly approach is inserted as well at the second input-field.
Hope this example helps you:
function NAN(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
}, 0);
}
}
}
/*
* a more user friendly approach
*/
function NAN2(cell) {
if (cell.value != '') {
var re = /^(0|[1-9][0-9]*)$/;
cell.value = cell.value[0]=='0'?+cell.value:cell.value;
if (re.test(cell.value) == false) {
alert('You must supply a numeric value greater than 0.');
cell.value = '0';
setTimeout(function () {
cell.select();
cell.focus();
markElement(cell);
}, 0);
}
else{
tickElement(cell);
}
}
}
function tickElement(cell){
cell.setAttribute('style','border: 1px solid green');
}
function markElement(cell){
cell.setAttribute('style','border: 1px solid red');
}
<p>
Your approach(onchange):
<input type="text" name="num" value="" onchange="NAN(this)"/>
</p>
<p>
Or you can use a more user friendly approach to notify an user right now when they are tipping something wrong (onkeyup):
<input type="text" name="num" value="" onkeyup="NAN2(this)"/>
</p>

Use of "this" keyword in javascript

I have read about "this" keyword and I learned that 'this' keyword works for the object which is in context.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid" required ><input type="submit"></label>
<div><button onclick="previewMessage()">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid() {
if (this.value == "fun") {
this.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
this.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML = myform.validationMessage;
}
</script>
</body>
</html>
But when I use oninput = "checkValid" , it should copy the checkValid function and the "this" keyword inside the function should point to input object.But that's not the case!!!
Check out this another piece of code, it means the same as the previous one, but runs normally.
<form id="myForm">
<label>Type anything but "fun": <input id="noFun" type="text" oninput="checkValid(this)" required ><input type="submit"></label>
<div><button onclick="previewMessage();">Preview errors</button></div>
<div id="err"></div>
</form>
<script>
function checkValid(input) {
if (input.value == "fun") {
input.setCustomValidity("You're having too much fun!");
} else {
// input is fine -- reset the error message
input.setCustomValidity('');
}
}
function previewMessage() {
var myform = document.getElementById("noFun")
document.getElementById("err").innerHTML=myform.validationMessage;
}
</script>
Can you explain me the difference between the two snippets and why the first example does not work as expected.
Thanks in advance!!!
But when i use oninput="checkValid" , it should copy the checkValid function and the "this" keyword inside the function should point to input object.
No, it shouldn't.
The value of an intrinsic event attribute is the body of the event handler function.
The HTML oninput="checkValid" is equivalent to the JavaScript:
reference_to_input.oninput = function (event) {
checkValue;
};
Mentioning a variable (like checkValue) without doing anything to it (like putting () after it to call a function) does nothing.
The way you've set up the event handler is such that the value of this will not be the <input> element. You've got what amounts to a "naked" function call, so this will refer to the window object.
If, however, you were to establish the event handler in JavaScript like this:
document.getElementById("noFun").oninput = checkValid;
you'd get this referring to the element.
Note that your code will pass the reference to the element as a parameter, which is why your second sample of code works.

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

Categories

Resources