I want to submit a form. But before that I wanna validate it. The validation is a javascript method. everything is ok as long as the javascript method is in the same .jsp file as the form.
But I want to put it to an external javascript file, and the method gets never called. Why?
this part should include the javascript into .jsp file.
<script type="text/javascript" src="Validate.js">
var val = new Validate();
var result= val.validateArticle();
</script>
here is the form I want to submit:
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return result" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
The Validate.js is in the same directory as the .jsp file.
here is the Validate.js (but it works fine, if it is in the .jsp file.)
function validateArticle() {
var a = document.forms["articleAnswerForm"]["art"].value;
var richtig = document.forms["articleAnswerForm"]["richtig"].value;
if (a == null || a == "" || a != richtig) {
alert("Nein " + a + " ist falsch");
return false;
}
}
so far the only thing that works is if I put everything into one .jsp file like below
<script type="text/javascript" >
function validateArticle() {
var a = document.forms["articleAnswerForm"]["art"].value;
var richtig = document.forms["articleAnswerForm"]["richtig"].value;
if (a == null || a == "" || a != richtig) {
alert("Nein " + a + " ist falsch");
return false;
}
}
</script>
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return validateArticle()" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
<form:form method="post" action="word.html">
<input type="submit" value="nächste Wort">
</form:form>
</c:if>
First, you cannot mix a src-ref and local code in one script tag.
<script type="text/javascript" src="Validate.js"></script>
<script type="text/javascript">
var val = new Validate(); // 'new Validate' won't work.
var result= val.validateArticle();
</script>
In HTML, onsubmit="return result" will probably not do what your are intended to. You want to validate on submit, won't you? So you have to call the validateArticle() function then, not on page load. And there is no need to instanciate a Validate object.
onsubmit="return validateArticle()"
This is all you need. You don't need to create an instance to use the Validation function.
Script:
<script type="text/javascript" src="Validate.js"></script>
HTML Form:
<form name="articleAnswerForm" action="answer.html"
action="answer.html" onsubmit="return validateArticle()" method="post">
Was is der Artikel?<br> <select name="art">
<option>???</option>
<option>der</option>
<option>die</option>
<option>das</option>
</select> <input type="hidden" name="richtig" value="${selected.article}">
<h1>${selected.german}</h1>
<input type="submit" value="Antworten">
</form>
So when you are moving Javascript to an external file. You don't need to do anything special to access it. There is no instantiation required. Just use the javascript as you would if it was included in the file itself. If you find it doesn't work, it's likely the file isn't loading properly, in which case check the file is in the right directory and the case of file is correctly set, as some file system are case sensitive.
Related
I have an input which on submit is redirecting to another page and i want this page to redirect to another using form input:
<form id="composeLink" method="post" name="composeLink" action="{$address}/" >
<input type="hidden" name="username" value="{$fields['username']}" />
<input type="hidden" name="password" value="{$fields['password']}" />
<input type="hidden" name="login" value="1" />
</form>
<script type="text/javascript">
//document.form.action = document.form.action.replace("http","https");
document.getElementById('composeLink').submit();
</script>
Action method of this form is send using smarty. The problem is that the link is not correct. Eg: current link is http://test.com and form action is http://action.com and the redirecting page has the link combined.
LE: the action form is send correctly
What can be the problem?
Problem is on your template engine, there is no problem, i mean on html. But you can write a javascript and solve that problem. If your action generated like that ( test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[1];
document.getElementById('composeLink').submit();
</script>
If your action generated like that ( http://test.com/http://action.com ), please write this one :
<script type="text/javascript">
var newAction = document.getElementById("composeLink").action.split("http://");
document.getElementById("composeLink").action = "http://" + newAction[2];
document.getElementById('composeLink').submit();
</script>
The different is your generated URL, if there is two "http" on your URL (For split), you have to use last code as i wrote
I'm trying to redirect a user to another page after clicking on a form submit button.
I'm trying to fire a few events which fill in certain parts of the form automatically then submit the form & finally redirect the user to another page.
Everything works expect the redirect. I have tried a few things but havent gotten the redirect to work after the form submits.
I also don't want to user to be redirected before the form has been successfully submitted.
Here is my code:
<form id="usp_form" method="post" enctype="multipart/form-data" action="">
<input class="usp_input" type="text" name="user-submitted-title" id="user-submitted-title" value="" />
<input class="usp_input" type="text" name="user-submitted-url" id="user-submitted-url" value="">
<input class="usp_input" type="text" name="user-submitted-tags" id="user-submitted-tags" value="">
<input class="usp_input" type="text" name="user-submitted-category" id="user-submitted-category" value="">
<textarea class="usp_textarea" name="user-submitted-content" id="user-submitted-content" rows="5"></textarea>
<input class="hidden" type="hidden" name="user-submitted-name" value="<?php echo $current_user->user_login; ?>">
<input onClick="copyText();copyText2();copyText3();handleClick();" class="usp_input" type="submit" name="user-submitted-post" id="user-submitted-post" value="Submit Post">
</form>
<script language="javascript" type="text/javascript">
function copyText3() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
document.getElementById("user-submitted-title").value = output1 + ', ' + output2;
}
</script>
<script language="javascript" type="text/javascript">
function copyText2() {
var output1 = document.getElementById("edit1").innerHTML;
var output2 = document.getElementById("edit2").innerHTML;
var output3 = document.getElementById("template").innerHTML;
document.getElementById("user-submitted-tags").value = output1 + ', ' + output2 + ', ' + output3;
}
</script>
<script language="javascript" type="text/javascript">
function copyText() {
var output = document.getElementById("templatebody").innerHTML;
document.getElementById("user-submitted-content").value = output;
}
</script>
<script language="javascript" type="text/javascript">
function handleClick() {
window.location.href='http://website.com/';
}
</script>
The submit button will launch a request, but you are also defining a redirecting request on the button press, so one will override the other (I'm not sure which one, it may depend on the browser).
You may want to fire an Ajax request instead of the standard submit, and do the redirection only when you get the response from the Ajax request so you are sure no information was lost.
You should not code like is but register your functions on the event, outside de HTML (it's always better to separate your HTML, JS and CSS).
You can understand about events bubling here : http://javascript.info/tutorial/bubbling-and-capturing
If you just want to see your code working and don't validate your form, just add "return false ;" at the end of your onclick attribute.
Edit : Oups sorry, you want submit your form, then redirect. You can do this with ajax requests (see http://www.w3schools.com/xml/xml_http.asp) : you submit your form in ajax, then you redirect.
But IMO, It's a serverside behaviour : you probably have a dynamic language (Python, PHP, ASP... ?) which process your form submission. It's here you have to redirect after the process.
How do I direct the browser to another URL based on user input for example:
abc.com/apple.html
abc.com/banana.html
abc.com/pear.html
BUT, if the user doesn't enter apple,banana or pear then they are directed to:
abc.com/wrong.html
Any help would be awesome! I only know HTML forms.
<form id='formName' name='formName' onsubmit='redirect();return false;'>
<input type='text' id='userInput' name='userInput' value=''>
<input type='submit' name='submit' value='Submit'>
</form>
<script type='text/javascript'>
function redirect() {
var input = document.getElementById('userInput').value;
switch(input) {
case 'apple':
window.location.replace('apple.html');
break;
case 'banana':
window.location.replace('banana.html');
break;
default:
window.location.replace('default.html');
break;
}
}
</script>
You may use Javascript/JQuery to do it like this:
HTML:
<form name="form_input" action="post_values.php" method="post">
<input type="text" name="fruit" id="fruit" />
<input type="submit" value="Submit" />
</form>
JS/JQuery:
<script>
$("form").submit(function() {
var fruit = $("#fruit").val();
if(fruit=='apple' || fruit=='pear' || fruit=='banana'){
window.location = "http://www.abc.com/"+fruit+".html";
}else{
window.location = "http://www.abc.com/wrong.html";
}
return true;
});
</script>
In the HTML file of "abc.com", which is mostly index.html, between your <HEAD> tags do this:
<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.abc.com/wrong.html">
Adjust content= to how many seconds you want your browser to wait before redirecting.
Update:
The http method is not recommended by W3C because of this:
If a page redirects too quickly (less than 2-3 seconds), using the "Back" button on the next page may cause some browsers to move back to the redirecting page, whereupon the redirect will occur again. This is bad for usability, as this may cause a reader to be "stuck" on the last website.
Hence the recommended method via JS:
<head>
<script>
function replaceDoc()
{
window.location.replace("http://www.abc.com/wrong.html")
}
</script>
</head>
I found the above method here:
W3Schools Window.Replace()
<script language="JavaScript">
var page = new Array("apple","banana","pear"); // list of your pages
function redirect(){
if(page.indexOf(document.forms["NameOfForm"]["NameOfInput"].value)!=-1){
window.location = document.forms["NameOfForm"]["NameOfInput"].value + ".html";
}
else {
window.location = "wrong.html";
}
return false;
}
</script>
<form name="NameOfForm" onsubmit="return redirect()">
<input name="NameOfInput" />
<input type="submit" />
</form>
put that code into abc.com/ and you just have to add, change the list of page ;)
I have a form and 2 javascript functions below but I am getting 2 '$ is defined' errors in my consoles. How can I fix these 2 errors which I have below (the errors are in the line which contains '//err' next to the line:
<body>
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload();' class='imageuploadform' >
<p class='imagef1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='imagef1_upload_form' align='center'><br/>
<label>Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label class='imagelbl'>(jpg, jpeg, pjpeg, gif, png, tif)</label><br/><br/>
<label><input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>
<label><input type='button' name='imageClear' class='imageClear' value='Clear File'/></label>
</p>
<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>
<script type="text/javascript">
var sourceImageForm;
function startImageUpload(imageuploadform){
//err $(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
$(imageuploadform).find('.imagef1_upload_form').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
//err $(sourceImageForm).find('.imagef1_upload_process').css('visibility','hidden');
$(sourceImageForm).find('.imagef1_upload_form').html(result + '<label>Image File: <input name="fileImage" class="fileImage" type="file"/></label><br/><label>(jpg, jpeg, pjpeg, gif, png, tif)</label><br/><br/><label><input type="submit" name="submitImageBtn" class="sbtnimage" value="Upload" /></label><label><input type="button" name="imageClear" class="imageClear" value="Clear File"/></label>');
$(sourceImageForm).find('.imagef1_upload_form').css('visibility','visible');
return true;
}
</script>
</body>
The $ variable is most often used by jQuery, which you don't appear to have on your page. This is not part of javascript; its a library. You need to include it with a script tag if you want to use it.
If you're using jQuery, you need to make sure this code comes after the where you include jQuery, and that it isn't run before document.ready.
Include jQuery above your functions. And, make sure they're loaded on page load as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" />
$(document).ready(function () {
// FUNCTIONS GO HERE
});
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)