Issue on Referencing $(this) to Multi Inputs on Submit Click - javascript

I am trying to create a simple Validation Function for validating User inputs at This Demo.
now my problem is using the $(this). to reference for each of the inputs which has same type. For example at this example I tried the
$('#email1').parent().after('<div class="err" role="alert">Can Not be Empty</div>');
which works but when I use the
$(this).parent().after('<div class="err" role="alert">Can Not be Empty</div>');
I am not getting any thing for validation
Here is the code which I have
<div class="form-group">
E-Mail 1: <input type="email" name="email1" id="email1"/>
</div>
<div class="form-group">
E-Mail 2: <input type="email" name="email2" id="email2" />
</div>
<button type="button" id="exe">Validate</button>
<script>
$(function() {
function emailInput(inputData) {
inputData = $.trim($(inputData).val());
if (inputData == "") {
$(this).parent().after('<div class="err" role="alert">Can Not be Empty</div>');
} else {
return inputData;
}
}
$("#exe").on("click",function(){
$(".err").hide();
if (emailInput($('#email1').val())){
alert($('#email1').val());
}
});
});
</script>

jQuery provides context to it's methods (i.e. what the value of this is), your function does not have this provided so this refers to window or the global scope. If you want to use this and have it refer to the current DOM node, you have to call your function using the call,apply or bind methods and provide the value of this as jQuery does.
// first argument is the context, i.e. what this refers to, subsequent arguments are your function arguments
emailInput.call($('#email1').get(0), $('#email1').val())
Here are some links to explain call, apply and bind:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

this is what I explained in the comments: DEMO
$(function() {
function emailInput(elem) {
inputData = $.trim(elem.val());
if (inputData == "") {
elem.parent().after('<div class="err" role="alert">Can Not be Empty</div>');
} else {
return inputData;
}
}
$("#exe").on("click",function(){
$(".err").hide();
if (emailInput($('#email1'))){
alert($('#email1').val());
}
});
});

The only problem with your code is that in your emailInput function there is no reference for this that is why your code is breaking at this point.
this works when an element is hit with an event and you bind it to the event handler. Only this element can be used with the this reference., for rest elements like parents children you need to use ids or any other selector. I hope this make it clear what you are doing wrong.

Related

Submit button to call function

My submit button is not doing anything when I click on it. I believe my event listener is correctly established. Any ideas on why it wont do anything?
JS FILE
document.getElementById("submitbutton").addEventListener("click", saveNames());
function saveNames() {
var player1name = document.getElementById("player1").value;
var player2name = document.getElementById("player2").value;
var player3name = document.getElementById("player3").value;
var player4name = document.getElementById("player4").value;
var player5name = document.getElementById("player5").value;
savePlayer(player1name);
savePlayer(player2name);
savePlayer(player3name);
savePlayer(player4name);
savePlayer(player5name);
gameScreen(2);
}
HTML FILE:
<input type="text"name="p1"><br>
<input type="text"name="p2"><br>
<input type="text"name="p3"><br>
<input type="text"name="p4"><br>
<input type="text"name="p5"><br>
<input id="submitbutton"type="submit" value="Submit">;
You're not binding to the function, you're binding to the result of the function. Just pass the function itself, don't invoke it. (Get rid of the parentheses):
document.getElementById("submitbutton").addEventListener("click", saveNames);
Why?
Because when that one line of code above executes, if you have the errant parentheses then the first thing it does is execute the saveNames function in order to get the result to pass to the addEventListener function. And that result is undefined because saveNames doesn't return anything.
Presumably also that first invocation of the saveNames function doesn't visibly do anything (though it does execute) because the inputs have no values in them yet at that time.
Consider as a contrived example:
doSomething( doSomethingElse() )
This would execute doSomethingElse() and then pass its returned result to doSomething(). The same is true when adding event listeners, you're just calling a function like any other function.
add the listener like this -
document.getElementById("submitbutton").addEventListener("click", saveNames);
note , I have removed () at end.
Use Id instead of name. you are reading these elements with id then you need to specify that.
Give a spaces before name or type.
//Remove the parenthese after "saveNames" - leaving them will call saveNames when it is encountered
document.getElementById("submitbutton").addEventListener("click", saveNames);
function saveNames() {
//Use an array as it's neater
var players = [
document.getElementById("player1").value,
document.getElementById("player2").value,
document.getElementById("player3").value,
document.getElementById("player4").value,
document.getElementById("player5").value
]
//loop and save
players.forEach(function(name) {
if (name) {
savePlayer(name);
}
});
//gameScreen(2);
}
function savePlayer(name) {
console.log(`${name} saved.`);
}
<input id="player1" type="text" name="p1"><br>
<input id="player2" type="text" name="p2"><br>
<input id="player3" type="text" name="p3"><br>
<input id="player4" type="text" name="p4"><br>
<input id="player5" type="text" name="p5"><br>
<input id="submitbutton" type="button" value="Submit">

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()) });
});

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

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