JavaScript, document.getElementById not grabbing from form? - javascript

I'm attempting to create a datetime-local input that will submit into a function that will convert it into different types later on. I've been attempting to check whether the function I am using is receiving the user input by throwing it into an alert, however every time I get the alert, the information is not displayed, with "[object HTMLInputElement]" in its place. Clearly I must be doing something wrong if my bugtest isn't even working properly
Below is my form and my script.
<form>
Start Time:
<input type="datetime-local" id="start">
End Time:
<input type="datetime-local" id="end">
<input type="submit" value="Send" onclick="convert()">
</form>
<script>
function convert() {
var sd = new Date(); //start date
var sds = new String();
var ed = new Date(); //end date
var eds = new String();
var sd = document.getElementById("start");
alert(sd);
var sds = document.getElementById("end");
alert(sds);
}
</script>
Does anything obvious stick out?

Simply calling getElementById will return an HTMLInputElement object. To get its value, you need to call .value
var sd = document.getElementById("start").value;
and
var sds = document.getElementById("end").value;
You also declared the variable sd twice. Only once is necessary. This adds to the codebase and makes things less DRY. Also, instead of initializing a new string like this
var eds = new String();
Do this instead
var eds = "";
I updated and improved your code.
var startValue = document.getElementById("start-value");
var endValue = document.getElementById("end-value");
function convert() {
var sd = new Date(); // start date
var ed = new Date(); // end date
var eds = new String();
var sd = document.getElementById("start").value;
startValue.innerHTML = sd;
var sds = document.getElementById("end").value;
endValue.innerHTML = sds;
}
<form>
Start Time:
<input type="datetime-local" id="start">
End Time:
<input type="datetime-local" id="end">
<input type="submit" value="Send" onclick="convert()">
</form>
<p id="start-value"></p>
<p id="end-value"></p>

YOu have declared the same variable twice, var sd. one time you assigned it a Date() function and the second time you have assigned it a document.getElementByID(). and yes what the gental men said, innerHtml need to included to get the value of the field.

First the click event is not the right chooce for what you are trying to achieve. Second youll have to bind events on the inpits rather then the form. You probably want to use a on change event. I also highly recommend using socument states and wleventbindings.

Related

Uncaught TypeError: projected.value is undefined

I'm currently trying to build a find and replace program using regular expressions in JavaScript, but I keep getting the following error when I click the "go" button, which is supposed to find and replace the given string, although currently all I'm trying to do is print the found string onto the console:
Uncaught TypeError: projected.value is undefined
Here's the code:
<body>
<textarea name="input" id="inputText" cols="30" rows="10">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
</body>
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find").value;
var toReplace = document.getElementById("replace").value;
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var regex = /toFind/;
var found = projected.value.match(regex);
console.log(found);
}
What am I missing?
The <p> element does not have a value property, but you can access its value the same way you updated it with the textContent property.
To match the value of the toFind input instead of exactly matching the "toFind" string, you need to use the variable in the regex.
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = projected.textContent.match(regex);
console.log(found);
}
You could also just reuse the input value directly:
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
You will also need to change the element selectors if you intend to get the current value of the inputs in the functions instead of just getting the initial value when the script loads:
var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");
Update the function to get the current value of the input when it's called:
function findNreplace() {
var regex = new RegExp(toFind.value, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
At end of this line "var projected = document.getElementById("projectedText")" write .value

Trying to set datetime-local using JavaScript

I am using the following code at this codepen to try to populate a datetime-local input element with today's data and time. What they have on this tutorial does not work. I also tried what is in this SO post but also does not seem to work. How do can I set the datetime to today's date and time into a datetime-local input element. Thank you.
HTML:
<input type="datetime-local" id="datetime" name="datetime">
JS:
let today = new Date().toISOString();
document.getElementById('datetime').value = today;
console.log(today);
You may try this:
let today = new Date();
today.setMinutes(today.getMinutes() - today.getTimezoneOffset());
document.getElementById('datetime').value = today.toISOString().slice(0, -1);
console.log(today);
<input type="datetime-local" id="datetime" name="datetime">
Try this. It's the example used on MDN:
const today = new Date().toISOString();
const dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = today;
Try this code.
Number.prototype.AddZero= function(b,c){
var l= (String(b|| 10).length - String(this).length)+1;
return l> 0? new Array(l).join(c|| '0')+this : this;
}//to add zero to less than 10,
var d = new Date(),
localDateTime= [(d.getMonth()+1).AddZero(),
d.getDate().AddZero(),
d.getFullYear()].join('/') +', ' +
[d.getHours().AddZero(),
d.getMinutes().AddZero()].join(':');
var elem=document.getElementById("LocalDate");
elem.value = localDateTime;
<input type="datetime-local" name="name" id="LocalDate">

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Make sure that an event execute after the actions of another one

Let's say that I've a file where I bind an event to some inputs, for parse and format date with moment.js, for example:
// plugins.js
$('.date').on('focusout', function() {
var thisInput = $(this);
thisInput.val( moment(thisInput.val()).format('YYYY-MM-DD') );
});
In my html file I've a script after the plugins.js call, in this script I use the parsed date to calculate the age from the date, assuming that the function has already executed in plugins.js:
<form>
<div class="form-group">
<label for="birth-date-input">Birth date</label>
<input type="text" id="birth-date-input" class="date">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="text" id="age">
</div>
</form>
<script src="plugins.js"></script>
<script>
jQuery(document).ready(function($) {
$('#birth-date-input').on('focusout', function() {
var thisInputVal = $(this).val();
var birthDate = moment(thisInputVal, 'YYYY-MM-DD');
var age = moment().diff(birthDate, 'years');
$('#age').val( age );
});
});
</script>
In my ideal word the .val() of the second script would be the assigned in the first, the parsed date. But the fact is that in both cases the value is the same, the only way I could make this work was with a dirty setTimeout().
$('#birth-date-input').on('focusout', function() {
setTimeout(function() {
var thisInputVal = $(this).val();
var birthDate = moment(thisInputVal, 'YYYY-MM-DD');
var age = moment().diff(birthDate, 'years');
$('#age').val( age );
}, 100);
});
Is there an alternative way to do this? To make sure that an event execute after the actions of another one [without setTimeout]...
You can call function which you want to execute first inside the second function before any other code. SO it has to execute first like.
function a()
{
alert("first");
return true;
}
function b
{
b();
alert("second");
}
or you can set an hidden variable on execution of first functin and check whether it is set or not in second one.

How to auto format textbox inputs

<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
</td>
</tr>
Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age.
The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.
Servlet for birthdate to Age
String birthdate = request.getParameter("birthdate");
int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
int yearDOB = Integer.parseInt(birthdate.substring(6, 10));
DateFormat dateFormat = new SimpleDateFormat("MM");
java.util.Date date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("dd");
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("YYYY");
date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
int calAge = thisYear - yearDOB;
if (thisMonth < monthDOB) {
calAge = calAge - 1;
}
if (thisMonth == monthDOB && thisDay < dayDOB) {
calAge = calAge - 1;
}
String age = Integer.toString(calAge);
Update in the form
<tr>
<td><label for="inputName">Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10" />
</td>
</tr>
Update in the source
<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>
Added Script
<script>
$('#input_date').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
</script>
I also tried the javascript but it's not working...
I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js http://firstopinion.github.io/formatter.js/demos.html This might be just the thing you're looking for.
This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.
new Formatter(document.getElementById('date-input'), {
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
or
$('#date-input').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.
// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/mm|dd/g, "\\d{2}")
.replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
https://jsfiddle.net/4msunL6k/
use datepicker api from jquery
here is the link Datepicker
and here is the working code
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
</td>
</tr>
<script>
$(function() {
$( "#birthdate" ).datepicker();
});
</script>
EDIT
$("input[name='birthdate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
this is the code that you may need
here is the fiddled code
user2897690 had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.
Here is my interpretation of their code with the added feature.
$("input[name='birthdate']:first").keyup(function(e){
var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
var key=chars.indexOf(e.keyCode);
console.log(key);
if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});

Categories

Resources