js / jquery object display just a quick flash - javascript

I am messing around with js objects today, ran across a weird glitch.
<form method="get" action="" name="start" >
<fieldset>
<label for="date">Date</label>
<input type="date" name="date" id="date" />
<div> </div>
<label for="smiles">Starting Mileage</label>
<input type="number" name="smiles" id="smiles" />
<div> </div>
<label for="stime">Starting Time</label>
<input type="time" name="stime" id="stime" />
<div> </div>
<label for="submit">Click To Save</label>
<input type="submit" name="submit" id="submit" />
</fieldset>
</form>
<div id="display" name="display" ></div>
`<script>src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">`
</script>
<script>
$(document).ready(function() {
$("#submit").click(function(){
var date = document.getElementById("date").value;
var smiles = document.getElementById("smiles").value;
var stime = document.getElementById("stime").value;
var record = { date2: date, smiles2: smiles, stime2: stime };
document.getElementById("display").innerHTML = smiles;
});
});
</script>
when you run this, the record.smiles flashes in the div id='display' but doesn't stay. Why? This is asking for more details, I don't know how much more in detail I can go, hopefully this will be enough verbage to make it happen.
Thanks.

It flashes and then disappears because you are clicking a submit button and the default action of a button on a form is to try and submit the form.
To prevent the default action you just need to add a single line of code:
$(document).ready(function() {
$("#submit").click(function(){
event.preventDefault(); // <----add this
var date = document.getElementById("date").value;
var smiles = document.getElementById("smiles").value;
var stime = document.getElementById("stime").value;
var record = { date2: date, smiles2: smiles, stime2: stime };
document.getElementById("display").innerHTML = smiles;
});
});
Also, you mentioned you are "playing around with javascript objects" so i just wanted to let you know that the code you have written here:
var record = { date2: date, smiles2: smiles, stime2: stime };
Could be completely removed and not affect the behavior of your program at all.
It is also unnecessary to add the "2" to your key name. They can just be the same as your variable if you want. Also, as a matter of style and readability formatting you object literals like this is slightly more readable if they become more complex. Have fun!
var record = {
date: date,
smiles: smiles,
stime: stime
};

You must prevent the default action of the submit button, otherwise it will submit the form at the same time, therefore reloading the page, try adding:
$("#submit").click(function(event) {
event.preventDefault()

Related

Adding two numbers together using HTML and Javascript

I'm trying to understand how to tie code and webpages together and stuff, so I mocked up this basic HTML page to add two numbers together using Javascript.
const first_n = document.getElementById("fnumber")
const second_n = document.getElementById("snumber")
window.onload = function solve(first_n, second_n) {
var solved = first_n + second_n;
document.getElementById("solution").innerHTML = solved
}
<body>
<form action="javascript:solve()">
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve">
</form>
<p id="solution"></p>
</body>
I know my nomenclature is a mess, don't judge. I just wanna see what I can get to work.
Thoughts on why this isn't working?
You need to call the solve function on click of the submit button. Secondly get the value of the input element inside the function
function solve(e) {
e.preventDefault();
const first_n = document.getElementById("fnumber").value
const second_n = document.getElementById("snumber").value
var solved = Number(first_n) + Number(second_n);
document.getElementById("solution").innerHTML = solved
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>
The window.onload event runs only once and that is when the page loads. At this time, the user has probably not entered any data, hence your fnumber and snumber will not contain any user entered values.
It would be better to trigger your solve function differently, for example associated with a button click via event listener or html on<> attributes
I have checked your code, please find the below fix.
const first_n = document.getElementById('fnumber');
const second_n = document.getElementById('snumber');
function solve() {
var solved = parseFloat(first_n.value) + parseFloat(second_n.value);
document.getElementById('solution').innerHTML = solved;
}
In your code you are not getting the input Values.
You will call the solve function when you click on the submit button and not on page load.
Solution
You need to convert the input values from a string to a number. by default the input values are stings.
const solve = e => {
e.preventDefault()
const firstNumber = Number(document.querySelector('#fnumber').value)
const secondNumber = Number(document.querySelector('#snumber').value)
document.querySelector('#solution').innerText = firstNumber + secondNumber
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>
Example of input default data type (default is string)
console.log(document.querySelector("#data").value, typeof(document.querySelector("#data").value))
<input type="number" id="data" value="3">
Even when the input type is type="number" the datatype will be a string.
Bonus
You can declare the solve() function on window.onload if you use an arrow function (=>) to declare it, it will not work if you declare the function using a normal function declare (function solve() { ... }).
window.onload = solve = (e) => {
e.preventDefault()
const firstNumber = Number(document.querySelector('#fnumber').value)
const secondNumber = Number(document.querySelector('#snumber').value)
document.querySelector('#solution').innerText = firstNumber + secondNumber
}
<form>
<label for="fnumber">First n:</label><br>
<input type="number" id="fnumber" value="3"><br>
<label for="snumber">Last n:</label><br>
<input type="number" id="snumber" value="5">
<input type="submit" value="Solve" onclick='solve(event)'>
</form>
<p id="solution"></p>
This has the benefit of running once the window is loaded so as you can see we have set the values of the inputs by default to be 3 and 5 once the example loads it will calculate them without clicking the solve button.

having trouble with javascript

Beginer to javasctipt. I am trying to write a simple calculation that will display some text if the time since oil change is past 6 months, the amount of oil left in the car is less then it started and finally display if everything is ok.
Thanks for the help
JavaScript
function oil(){
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.oil.result.write(aa);
}else{
document.oil.result.write("Everything Is all good");
}
}
HTML
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick = oil()>
<input name=result readonly>
</form>
There are a couple of problems with your code
Missing Form close tag
Your controls don't have IDs
missing quotes on the result input
Don't need to use a submit input when you're not submitting to a form. Try button
Not sure what document.oil.result.write(aa); will do. I think the correct process is to get the input using document.getElementById and then set the value of the control
I will try to answer your question with the least number of line changes. This is not the optimal answer. Comments have been added to help you understand required changes. Your HTML and JavaScript are invalid, so it was a surprise to me how they both ran on Chrome.
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function _oil(){ // oil() conflicts with your form's name
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.write(aa); // you can't .write() to an element
}else{
document.write("Everything Is all good");
}
window.event.preventDefault(); // so your window does not load the same page when you submit
return false;
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick ="_oil()"> <!-- you must enclose the onclick attribute, even if both work -->
<input name=result readonly>
</body>
</html>
May be like this:
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function oil(){
var start = document.getElementsByName("start")[0].value;
var lastOilChange = document.getElementsByName("time")[0].value;
var totalOil = document.getElementsByName("amount")[0].value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.getElementsByName("result")[0].value = aa;
}else{
document.getElementsByName("result")[0].value = "Everything Is all good";
}
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="thisform">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="button" value="go" onclick = oil()>
<input name=result readonly>
</form>
</body>
</html>
!!! The form name can not use oil
What you want is to set the value of the form field rather than trying to use write:
if( lastOilChange > 6 || start < totalOil){
document.oil.result.value = aa;
} else {
document.oil.result.value = "Everything Is all good";
}
As pointed out in other answers, though, you also need to prevent the form from trying to submit information to the server and reload the page. There are several ways of doing this (see e.g. JavaScript code to stop form submission). One is to replace the submit button with an ordinary button (<input type="button" value="Calculate" />).
Another is to attach your function to the form as an event handler, and return false at the end of it.
document.oil.onsubmit = function () {
...
return false;
}
(JSFiddle)

AJAX function not being called with button onclick function

I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.

Dynamically Update fields through Input field and dropdown

I'm trying to dynamically update a text field through an input field. This will then be linked to a dropdown selection with values. I also need to show a due date to show 30 days in advance from today's date.
Here is my HTML:
<div>
<label for="payment">Payment:</label>
<input type="text" name="amount" id="amount" onChange="myfunction()"/>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
<option value="1">Fast</option>
<option value="2">Medium</option>
<option value="3">Slow</option>
</select>
</div>
<br />
<div>
Payment Breakdown: <br /><br />
Payment:
<div name="amount" id="amount"></div>
Freight:
<div name="delivery" id="delivery"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
</div>
I'm struggling with the Javascript part though and fitting it all together.
I've gotten as far as this and now I'm stuck. (Not very far I know)
function myFunction()
{
var amount = document.getElementById("amount");
var delivery = parseInt($(this).find("option:selected").val());
total = amount + delivery
$("#total").html(total);
};
I've looked at examples on Stackoverflow and Google but nothing seems similar to what I'm trying to achieve. Although I know the answer is out there, I'm not sure if I'm asking the right question.
Cheers
I would change it to this. Here I have an updateCost() function which is called when the amount is changed or the delivery is changed. I also added code to handle the due date.
Remove the inline onchange event from the amount:
<input type="text" name="amount" id="amount"/>
Javascript:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = amount + delivery
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
// handle the due date
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30);
var dateStr = todayPlus30.getDate() + "/" + (todayPlus30.getMonth()+1) + "/" + todayPlus30.getFullYear();
$('#date').html(dateStr);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
Your original code has a few problems:
The wrong case on the inline function call
The use of this within the function when this is not actually any of your elements (you didn't pass it as an argument).
The use of amount in the calculation when amount is an input element, not a value.
From a usability point of view, it would only try to update when the amount is changed, I think it would be better to update on both change of the amount and delivery.

Trying to find selected radio button. What's wrong?

I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.

Categories