Add days to user inputed date in Javascript - javascript

So I've run into a snag trying to make a date calculator in Javascript. I'm fairly new to Javascript so I feel like I'm diving in a little deep, but here's a rundown of what I'm trying to accomplish.
Here's a jsfiddle: http://jsfiddle.net/b52hamw7/2/
I first have a form in my HTML formatted as follows:
<form>
<p class="instructions">I need my items by:</p><br>
<input type="date" name="date" value="" id="date"/>
<input type="button" value="Submit" id="submit">
</form>
<p>Be sure to order by:</p><p id="dateoutput"></p>
The idea here is that a user will input a date into the form and then a javascript code will add 10 days to it and output the day that they need to order by, formatted as a date.
Here's the script that I have so far, which I know isn't close to working, but it's a start I guess:
<script>
document.getElementsByName("submit").onclick = function() {
var dateIn = document.getElementsById("date").value;
var addDays = 10;
var dateOut = dateIn + addDays;
};
document.getElementById("dateoutput").innerHTML = dateOut;
</script>
I really appreciate any direction you can give me on this one. Thanks in advance!

There are multiple typos and issues in your code. I will list some of them below to get you on the right track.
1) Your line document.getElementsByName("submit").onclick.... is attempting to search for an element with name="submit" of which you have none in your HTML.
2) The next line var dateIn = document.getElementsById("date").value; has a typo, it should be: document.getElementById("date").value. You have an extra 's'.
3) The line document.getElementsById("dateoutput").innerHTML = dateOut; has 3 problems. First you have the extra 's' as in point 2 above. Second, you are attempting to assign the innerHTML to the value of variable that you have lost scope for. And Finally it is not executed within the context of the click function and is executed immediately when it is parsed as opposed to when the click event occurs. Therefore it needs to be moved within your onclick handler function.
4) With respect to adding days to the date. Please check out Add days to JavaScript Date. Right now you are attempting to to add 10 to a string value that you are pulling from the input element which simply concatenates the string '10' onto the end of your date string. You need to convert it to a date object and then add the 10 days. This is explained in code examples in the link provided

Related

How to write a function that adds a function inside a function in a string?

I'm going to try my best to explain this string manipulation.
I would like to write a JavaScript function that takes a string (preferably from a message textbox but it will be initially stored in a variable for this example) and looks for every instance of the power function "Pow()". Then, takes the contents of the "base" portion of the power function "Pow(base,exponent)" and replace it with the absolute function "Abs()" with the contents inside that so the result is "Pow(Abs(base),exponent)". The base can be anything; a word, an equation, or another function. result out to another message textbox.
for example
input:
return(1.0-step(snoise(vec2(5.0*pow(iGlobalTime,2.0)+pow(uv.x*7.0,1.2),pow((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0,staticHeight))),staticAmount))*staticStrength;
output:
return(1.0-step(snoise(vec2(5.0*pow(abs(iGlobalTime),2.0)+pow(abs(uv.x*7.0),1.2),pow(abs((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0),staticHeight))),staticAmount))*staticStrength;
I'm well aware of the .match and string.replace() functions but this is a little more complex.
Can anyone lead me in the right direction?
<textarea id = "output" rows="25" cols="55" ></textarea>
<script>
inputStr = "return(1.0-step(snoise(vec2(5.0*pow
(iGlobalTime,2.0)+pow(uv.x*7.0,1.2),pow
((mod(iGlobalTime,100.0)+100.0)*uv.y*0.3+3.0,
staticHeight))),staticAmount))*staticStrength;"
function baseReplacer(input)
{
}
var outputStr = baseReplacer(inputStr);
document.getElementById("output").value = outputStr;
</script>
I will try to describe the pseudo algorithm:
For every match of the substring pow(:
From the next position, you either will find nested brackets in first argument, or a simple argument, and then a comma.
If you find brackets, iterate through each position adding +1 to a counter every open bracket, and -1 for every close bracket. When the counter is set to zero, next comma is sure to end the first parameter string.
Got the idea ?
Happy 2020 ;)

multiplication inside an input with "*" operator

I am trying to get a multiplication entered in an input replaced by its solution.
Basicaly, when you enter 3*3 into the input, I would like my javascript code to replace 3*3 by 9.
Probably not so hard to obtain but I'm a total noob with javascript here. I get this so far, but I should miss a crucial point!
Thanks for your help :)
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = Number(array[0]*array[1]);
document.getElementById("res").value = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <input type="text" id="res" readonly>
Your code actually works as it is now. Just make sure you tab out of the input field after typing in the equation and you'll see it do its job. That's because your code is running on the blur event, which is when the focus leaves an element.
But, as far as your conversion code goes:
Number(array[0]*array[1])
Attempts to convert the product of array[0] and array[1], when what you need is to convert each array value to a number first and then do the math.
Number(array[0]) * Number(array[1])
Now, instead of Number(), you can just prepend a + to each value that needs conversion.
+array[0] * +array[1]
But, in reality, anytime you attempt to do multiplication, division or subtraction on strings, they are automatically converted to numbers, so you really don't even need that here.
Lastly, since you are just displaying the result and don't want the user to be able to modify it, just put it into a regular element, like a span instead of a form field element that you then have to set to readonly. Form fields are primarily for collecting information, not displaying it. When you do work with a non-form field element, you don't use the value property, you use .textContent (when there is straight text) or .innerHTML (when the string contains HTML to be parsed).
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = array[0] * array[1];
document.getElementById("res").textContent = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <span id="res"></span>

Alternative in regular expression's ending

I have the following DOM structure:
<form>
<input type="text" id="a">
<button>Submit</button>
</form>
or:
<form>
<input type="text" id="a">
</form>
which one depends on what user have done, it's created dynamically.
I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?
I tried the following:
'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'
But it doesn't work, because it displays empty string as a result.
var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:
var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");
// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
$form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
$lastInput.after($newInput);
}
You should not parse HTML using Regexp. No, seriously.
That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):
(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)
Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.

Trying to multiple two numbers entered in text fields and alert the answer using jquery

Very new to javascript and jquery. Attempting an exercise and came up with this code which I was hoping would take the two numbers a user enters into text fields and on clicking the multiply button, it would alert() the answer.
<body>
<script>
$(document).ready(function(){
var first = $('#first').value;
var second = $('#second').value;
$('#multiply').click(function(){
alert(first*second);
}); // end click
}); // end ready
</script>
First Number:
<input type="text" id="first"><br >
Second Number:
<input type="text" id="second"><br >
<input type="button" id="multiply" value="Multiply">
<input type="button" id="divide" value="Divide">
</body>
I'd suggest:
$(document).ready(function(){
$('#multiply').click(function(){
var first = parseFloat($('#first').val());
var second = parseFloat($('#second').val());
console.log(first*second);
}); // end click
}); // end ready
val() is used to get the value from a jQuery object (or the value of the first element of a jQuery collection),
parseFloat() is used to convert the <input/> elements' string into a number.
Incidentally, I'm using console.log(), instead of window.alert(), in order to be less frustrating the user. But, obviously, change that to your own taste (but logging to the console doesn't require a user-action to dismiss).
References:
JavaScript:
parseFloat().
jQuery:
val().
There is no value property in a jQuery object, use the val method to get the value from the inputs:
var first = $('#first').val();
var second = $('#second').val();
Right now you have the code for getting the values when the page loads, but you should get the values when the click happens:
$(document).ready(function(){
$('#multiply').click(function(){
var first = $('#first').val();
var second = $('#second').val();
alert(first * second);
}); // end click
}); // end ready
You are using implicit conversion from strings to numbers when you do the multiplication. You might want to explicitly parse the strings, it's good practice to make sure that the data is of the correct type rather than relying on implicit conversions. If you for example want to add numbers, the implicit conversion won't work there, as the + operator also is used to concatenate strings. Use the parseInt or parseFloat methods to parse strings into numbers. Example:
var first = parseInt($('#first').val(), 10);
var second = parseInt($('#second').val(), 10);
When you grab the value of a text field, the result is text. Not a number. You can parse the value into a number with the (globally available) parseFloat function (Or the parseInt function if there is no fractional value to the numbers).
var first = parseFloat($("#first").val());
var second = parseFloat($('#second').val());
$('#first') is a jQuery object, so you should use the .val() method. On the other hand, you are setting the variables when the DOM is ready, so it's not updating it when the user clicks.
$(document).ready(function () {
var first, second;
$('#multiply').click(function () {
first = $('#first').val();
second = $('#second').val();
alert(first * second);
});
});
In other things, your script tags should be at the end of the body. Script parsing is synchronous so the browser takes more time to get the DOM ready.
Have fun! :)

Type Casting in Apps Script

First time on StackOverFlow!
I am working on building an app that takes in a value through a UI Form TextBox. Once that form is submitted it calls a method that then appends a "/" to the value. The problem is that .append() is not available, because getElementById() returns a GenericWidget object and thus cannot be operated on as if it were a string. I have tried type casting it use .toString() in the var userinput = app.getElementById('input').toString; call and afterward using userinput = userinput.toString.
I have been working with Apps Script for about a month and a few days now and I think that casting to a different type other than GenericWidget would be helpful for anyone who wants to modify a value in a type specific way after passing the value to another method.
I have also done a good bit of research trying to find a solutiong for my problem but like a couple times in the past working with Apps Script I find that since it is a younger language there isn't as much helpful information as there is with languages like Javascript, HTML, and XML. Any help is appreciated.
You have to get the textBox value using e.parameter.textBoxName an then re-assign a value to the textBox. A short example will be more explicit
function doGet(){
var app = UiApp.createApplication();
var textbox = app.createTextBox().setName('txt').setId('txt')
// add other elements, handlers, callBackElements, etc...
}
function changetext(e){
var app = UiApp.getActiveApplication();
var textBoxValue = e.parameter.txt ; // get the value in the text box
var txtBoxWidget = app.getElementById('txt') ; get the widget by its ID
txtBoxWidget.setText(textBoxValue+'/'):// assign the modified value
return app ;// update the UI with new value
}

Categories

Resources