Calling Javascript from a html form - javascript

I am basing my question and example on Jason's answer in this question
I am trying to avoid using an eventListener, and just to call handleClick onsubmit, when the submit button is clicked.
Absolutely nothing happens with the code I have.
Why is handleClick not being called?
<html>
<head>
<script type="text/javascript">
function getRadioButtonValue(rbutton)
{
for (var i = 0; i < rbutton.length; ++i)
{
if (rbutton[i].checked)
return rbutton[i].value;
}
return null;
}
function handleClick(event)
{
alert("Favorite weird creature: "+getRadioButtonValue(this["whichThing"]));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="myform" onSubmit="JavaScript:handleClick()">
<input name="Submit" type="submit" value="Update" onClick="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
</body>
</html>
edit:
Please do not suggest a framework as a solution.
Here are the relevant changes I have made to the code, which results in the same behavior.
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.myform['whichThing'])));
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye">;
<input name="Submit" type="submit" value="Update" action="JavaScript:handleClick()"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

You can either use javascript url form with
<form action="javascript:handleClick()">
Or use onSubmit event handler
<form onSubmit="return handleClick()">
In the later form, if you return false from the handleClick it will prevent the normal submision procedure. Return true if you want the browser to follow normal submision procedure.
Your onSubmit event handler in the button also fails because of the Javascript: part
EDIT:
I just tried this code and it works:
<html>
<head>
<script type="text/javascript">
function handleIt() {
alert("hello");
}
</script>
</head>
<body>
<form name="myform" action="javascript:handleIt()">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>

In this bit of code:
getRadioButtonValue(this["whichThing"]))
you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.
EDIT
To get the value out of the radio buttons, grab the JQuery library, and then use this:
$('input[name=whichThing]:checked').val()
Edit 2
Due to the desire to reinvent the wheel, here's non-Jquery code:
var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
if (document.myform.whichThing[i].checked==true) {
t = t + document.myform.whichThing[i].value;
}
}
or, basically, modify the original line of code to read thusly:
getRadioButtonValue(document.myform.whichThing))
Edit 3
Here's your homework:
function handleClick() {
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
//event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body>
<form name="aye" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="Update" />
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.
In the function itself, I modified the how the form was being accessed. The structure is:
document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.
The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.
EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.
See the difference in this method:
function handleClick() {
alert("Direct Access: " + document.aye["whichThing"]);
alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
return false; // prevent further bubbling of event
}

Pretty example by Miquel (#32) should be refilled:
<html>
<head>
<script type="text/javascript">
function handleIt(txt) { // txt == content of form input
alert("Entered value: " + txt);
}
</script>
</head>
<body>
<!-- javascript function in form action must have a parameter. This
parameter contains a value of named input -->
<form name="myform" action="javascript:handleIt(lastname.value)">
<input type="text" name="lastname" id="lastname" maxlength="40">
<input name="Submit" type="submit" value="Update"/>
</form>
</body>
</html>
And the form should have:
<form name="myform" action="javascript:handleIt(lastname.value)">

There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).
The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.
<!DOCTYPE html>
<html>
<head>
<title> Semester Results </title>
</head>
<body>
<h1> Semester Marks </h1> <br>
<script type = "text/javascript">
function checkMarks(total)
{
document.write("<h1> Final Result !!! </h1><br>");
document.write("Total Marks = " + total + "<br><br>");
var avg = total / 6.0;
document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
if(avg >= 90)
document.write("Grade = A");
else if(avg >= 80)
document.write("Grade = B");
else if(avg >= 70)
document.write("Grade = C");
else if(avg >= 60)
document.write("Grade = D");
else if(avg >= 50)
document.write("Grade = Pass");
else
document.write("Grade = Fail");
}
</script>
<form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
Semester 1: <input type = "text" id = "s1"/> <br><br>
Semester 2: <input type = "text" id = "s2"/> <br><br>
Semester 3: <input type = "text" id = "s3"/> <br><br>
Semester 4: <input type = "text" id = "s4"/> <br><br>
Semester 5: <input type = "text" id = "s5"/> <br><br>
Semester 6: <input type = "text" id = "s6"/> <br><br><br>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>

Remove javascript: from onclick=".., onsubmit=".. declarations
javascript: prefix is used only in href="" or similar attributes (not events related)

Related

Form Submit with JS Not Posting to Controller

I would like to 'post' a form with vanilla JS. There are other questions similar, but I cannot get mine to work. The data is simply not passing to the controller.
I have several options for user on page, displayed as buttons. When the user clicks one button, a hidden form gets filled, and then the JS will submit the form to the controller.
the hidden form below:
[for testing, I have not 'hidden' the form fields yet, so I can monitor the correct information is getting to the form]
<form action="RetailTimePriceDisplayOne" method="post" id="postForm" name="postForm">
<input type="text" id="fmZero" value="#ViewBag.zero" />
<input type="text" id="fmVehicle" />
<input type="text" id="fmTeam" />
<input type="text" id="fmTLabor" />
<input type="text" id="fmRouteCost" />
<input type="text" id="fmRouteD" value="#ViewBag.vehicleMile"/>
<input type="text" id="fmRouteT" value="#ViewBag.vehicleTime"/>
</form>
My JS:
<script>
function fillForm(vehicleType, teamCount, travelLabor, routeCost) {
document.getElementById("fmVehicle").value = vehicleType;
document.getElementById("fmTeam").value = teamCount;
var x = #ViewBag.rateTravelDrvr;
if (teamCount > 1) {
x = #ViewBag.rateTravelDrvr + (#ViewBag.rateTravelCrew * (teamCount - 1));
}
document.getElementById("fmTLabor").value = x;
var y;
if (vehicleType == "V") {
y = #ViewBag.vVPrice;
}
if (vehicleType == "H") {
y = #ViewBag.vHPrice;
}
if (vehicleType == "T") {
y = #ViewBag.vTPrice;
}
document.getElementById("fmRouteCost").value = y;
SubmitForm();
}
function SubmitForm() {
var myForm = document.getElementById('postForm');
//document.forms["postForm"].submit();
myForm.method = 'post';
myForm.submit();
}
</script>
The form gets filled correctly, but no data is submitted to the controller. You can see that I played around with it a bit. One thought I had was that the method was changing to 'get' and that by explicitly specifying the method, I might solve the issue. But no such luck. Thanks!
EDIT:
As requested, one of the 6 buttons on the page that fire the JS function.
<button class="btn btn-secondary btn-lg" style="width:100%; height:100%;" onclick="fillForm('T',3)">
<strong>#ViewBag.TrkThr</strong>
<p>with 3 persons</p>
<p>+ #ViewBag.TrkMinute per labor minute*</p>
</button>
Usually when I want to submit the form, I am using button, then do onClick event
The "name" of the inputs wasn't defined, and hence data wasn't getting posted.

html sending parameters to function from id

I'm an absolute beginner and tried to find similar questions but couldn't. Apologies if this has been answered previously.
In my assignment we need to create a form with 2 text fields and 1 button. The fields are for height and width and the idea is that onclick on the button will send the 2 parameters to a function that will change the height + width attributes for a photo. I know I'm doing something wrong because the picture simply disappears. Ideas? Thanks!
<html>
<head>
<script>
function borderResize(height1, width1)
{
document.getElementById('Amos').height = height1;
document.getElementById('Amos').width = width1;
}
</script>
</head>
<body>
<img src="Amos.jpg" id="Amos" />
<form>
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" value="click!" onclick="borderResize('height.value', 'width.value')"/>
</form>
</body>
</html>
When you write
onclick="borderResize('height.value', 'width.value')"
in means that on click borderResize function will be invoked with two string arguments, literally strings "height.value" and "width.value". In your case you want something like this
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
In above case you are selecting element from DOM using getElementById method and then read its value property.
You should learn to use addEventListener(), I would recommend you not to use ugly inline click handler.
The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on.
Here is an example with your code.
window.onload = function() {
document.getElementById('button').addEventListener('click', borderResize, true);
}
function borderResize() {
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}
<img src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/s200x200/11034289_10152822971918167_2916173497205137007_n.jpg?oh=71de7a46a75a946cf1d76e5ab10c1cdc&oe=55889977&__gda__=1434173455_6127f174627ed6014c84e562f47bc44c" id="Amos" />
<input type="text" id="height" placeholder="Height" />
<input type="text" id="width" placeholder="Width" />
<input type="button" id="button" value="click!" />
However as for your immediate problem you can use
onclick="borderResize(document.getElementById('height').value, document.getElementById('width').value)"
onclick="borderResize('height.value', 'width.value')"
here you pass to borderResize strings: 'height.value', 'width.value'.
You may get value of input from function:
function borderResize(height1, width1)
{
document.getElementById('Amos').height = document.getElementById('height').value;
document.getElementById('Amos').width = document.getElementById('width').value;
}

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.

Function call repeating itself

I've just started JavaScript and I am facing a problem. I've written a script in which I am calling a function. I don't know why this script is calling itself twice.
The code is as below:
<html>
<head>
<script type="text/javascript">
var randomNo1 = Math.floor(Math.random()*10);
var randomNo2 = Math.floor(Math.random()*10);
window.onload = ask;
function ask()
{
alert("How much " + randomNo1 + " times " + randomNo2 + "?");
}
function question()
{
var product = randomNo1 * randomNo2;
var stdAnswer = document.getElementById('answer').value;
if(stdAnswer == product)
{
alert("Very good!")
//generate new nos
randomNo1 = Math.floor(Math.random()*10);
randomNo2 = Math.floor(Math.random()*10);
ask();
}
else
{
alert("No. Please try again.");
ask();
}
}
</script>
</head>
<body>
<form>
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>
</body>
</html>
Add action="#" to your form, to avoid page being refreshed when form is submitted.
<form action="#">
Enter answer: <input type="text" id="answer" />
<input type="submit" value="Check" onClick="question()" />
</form>​
You call it twice, once at startup window.onload = ask; and once in question
[edit]
note too that you don't have a ; after the first alert() in question()
[/edit]
Because your button is a submit button. When clicked it runs click handlers (if specified), then posts the form. So you call ask() twice. One time in a click handler, and another time in a window.onload handler.
After this form is submitted, page simply reloads (because it has no associated action). And onload handler is fired again.
You can see it here: http://jsbin.com/ukusof.
Your form as no method nor action. When you click your submit button, the page refresh itself, thus firing ask again.
You're submitting the form, which loads the page again, so ask will be fired again on load.
You have a form with a submit button. With no action in the form, it resubmits the page. You can stop this with
<input type="submit" value="Check" onClick="question();return false" />

Categories