JavaScript Form Validation Not working properly - javascript

This is my HTML/Javascript Code.I am submitting the filled form to a Servlet. There seems to some problem with the form validation. I am not able to figure out why. It is supposed to prompt me to enter a new value if I enter 0 in textbox2 and select Divide from the drop down list box. But it doesn't and the form is submitted without any prompting to the servlet which throws Exception due to division by zero.
<html>
<head>
<title>A simple calculator</title>
<script language="text/javascript">
function validate(b,op)
{
var newval=b;
if(b=="0"&&op=="/")
newval=prompt("Enter a non-zero value for B:",1);
document.CalculatorForm.textbox2.value=newval;
}
</script>
</head>
<body>
<form name="CalculatorForm" method="get" action="http://localhost:8080/hello/CalculatorServlet" onsubmit="validate(this.textbox2.value,this.dropdown.options[this.dropdown.selectedIndex].value);">
A:<input type="text" name="textbox1" id="T1" /><br>
B:<input type="text" name="textbox2" id="T2" /><br>
Operation<br>
<select name="dropdown" id="dd">
<option value="+">Add</option>
<option value="-">Subtract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<br>
<input type="submit" value="compute"/>
</form>
</body>
</html>

Change the function to:
function validate()
{
var b = document.getElementById('T2').value;
var op = document.getElementById('dd')
var opValue = op.options[op.selectedIndex].value;
if(b=='0' && op=='/')
//do something
else
// submit
}

Related

Clear submitted form using JavaScript

I know this is continuously asked anew, and I've checked out different answers and tried different solutions but to no avail.
I just have to build a form that takes as input the cylinder ray and it height and then find the volume when we click a button.After finding it, shuold be cleared all fields with another button .The function to calculate volume it is working fine, but not the function that clear inputs.
Here is the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript">
function llogarit() {
var rreze = parseInt(document.getElementById("val1").value);
var lartesi = parseInt(document.getElementById("val2").value);
var rez = document.getElementById("llogarit");
rez.value = (Math.PI * Math.pow(rreze, 2) * lartesi);
}
function fshij() {
document.getElementById("val1").value.clear();
document.getElementById("val2").value.clear();
document.getElementById("llogarit").value.clear();
}
</script>
</head>
<body>
<form>
<p>Vendos 2 vlera</p>
<p>rreze
<input type="text" name="rreze" id="val1" value="2" /></p>
<p> lartesi
<input type="text" name="lartesi" id="val2" value="2" /></p>
<p> Vellimi
<input type="text" name="vellimi" id="llogarit" value="" /></p>
<input type="button" onclick="llogarit()" value="llogarit" />
<input type="reset" value="fshij" onclick="fshij()" />
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
You can reset all form controls in one form with reset method.
// <form name="FORM_NAME">
document.forms["FORM_NAME"].reset();
Try the following:
document.getElementById('myInput').value = ''
Try the follow and add a div tag to the code
<div class="yourClass">
<button onclick="cdClear();" class="yourClass">Clear</button>
</div>
Note: In HTM, you can replace the class with id if you have already coded.
<script type="text/javascript">
function cdClear(){var a=document.getElementById("codes");a.value="",a.focus(),</script>

Why do my JavaScript calls not work in a form after switching the doctype to HTML5

I have a form that uses JavaScript to reveal additional fields depending on user selections. The code worked fine using the XHTML 1.1 doctype (not my choice... lame school project guidelines), but after switching to the HTML5 doctype nothing works. The only way I can get any JavaScript to work inside the form is to put it directly in the onchange="" setting; just adding the function call there will not work. I've tried event listeners also, and that doesn't work either.
For simplicity's sake I'm only showing code for one of the dynamic fields:
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
document.getElementById("visitor").addEventListener("change", function(ev) {
Visitor();
});
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
document.getElementById("vother").innerHTML=(othertext);
}
}
</script>
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor" onchange="Visitor();">
<option value="" disabled selected style="display:none;">select...</option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
</body></html>
I'm aware that other people have asked similar questions, but none of the answers I've found work for me.
I verified some issues in your code:
this line is not valid (syntax error):
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
You should escape the double quotes, or replace them with single quotes.
This will work:
var othertext = "<label>What would you consider yourself?</label><br/><input type=text name='other_visitor' id='other_visitor' />";
Get rid of the inline onchange="Visitor(); binder or the document.getElementById("visitor").addEventListener. You should choose one of the approachs.
move your <script> tag to the bottom of your body (just before </body>). Or wrap your code into DOMContentLoaded event (IE9+).
(optional). You don't need parenthesis around (othertext) here:
document.getElementById("vother").innerHTML = (othertext);
Working code: https://jsfiddle.net/mrlew/txk11m6c/
You should put your script at bottom like given below or use window.onload.
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor" onchange="Visitor();">
<option value="" disabled selected style="display:none;">select...</option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
<script type="text/javascript">
document.getElementById("visitor").addEventListener("change", function(ev) {
Visitor();
});
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type="text" name="other_visitor" id="other_visitor"/>";
document.getElementById("vother").innerHTML=(othertext);
}
}
</script>
</body></html>
Here's my two cents:
<!DOCTYPE html>
<html><head>
<?php include "phpself.php"; ?>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() { // ~ F I X ~ Run code when the rest of page is done loading instead of immediately when browser reads it. This is a very common problem I've noticed newbies have with JS
document.removeEventListener("DOMContentLoaded",this); // Remove event after it's served purpose
document.getElementById("visitor").addEventListener("change", Visitor); // Also removed redundant function, Visitor can already be called by itself
function Visitor() {
var visitor = document.getElementById("visitor").value;
if (visitor=="Other") {
var othertext="<label>What would you consider yourself?</label><br/><input type=\"text\" name=\"other_visitor\" id=\"other_visitor\"/>"; // Backslashed quotations that were clearly meant to be included part of string
document.getElementById("vother").innerHTML=(othertext);
}
}
});
</script>
</head><body>
<form action=\"".getPHPSelf()."\" enctype="text/plain" method="post" onsubmit="return FormValid();" >
<fieldset style="width=50%;">
<legend>Comments</legend>
<label>I am a:</label>
<select name="visitor" id="visitor">
<option value="" disabled selected style="display:none;">select... </option>
<option value="Friend">Friend</option>
<option value="Client">Client</option>
<option value="Other">Other</option>
</select>
<br/><br/><div id="vother"></div>
<input type="submit" value="Submit"/><input type="reset" value="Reset"/>
</fieldset>
</form>
</body></html>

JQuery to Submit a Form - Spot the Error

I've checked here and here but can't get my form to submit. (noob to Jquery...)
<html>
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
//alert(subject_id)
//document.forms["choose_subject"].submit();
$('#choose_subject').submit();
//$('form#choose_subject').submit();
//$('form#choose_subject')[0].submit();
//alert(subject_id);
//document.getElementById("choose_subject").submit();
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
<option value="1">a</option>
<option value="2">a2</option>
</select><input type="submit" name="submit" value="Choose Subject"/>
<BR />
</FORM>
<!-- CREATE SUBJECT -->
<FORM action="/subjects" id="create_subject" method="POST">
<BR /><BR />
Create a new Subject
<input type="text" name="subject_name" />
<input type="submit" name="submit" value="Create Subject" />
</FORM>
<body>
</html>
I've tried each of these methods:
1) document.forms["choose_subject"].submit();
2) $('#choose_subject').submit();
3) $('#choose_subject')[0].submit();
4) $('form#choose_subject').submit();
5) $('form#choose_subject')[0].submit();
6) document.getElementById("choose_subject").submit();
The first and last result in a "TypeError: document.forms.choose_subject.submit is not a function.
The second and fourth don't have an error but they also doesn't do anything.
The third and fifth error out with a "TypeError: $(...)[0].submit is not a function"
If I remove the second form these results hold true.
Clicking the submit button works as expected.
Change your the name of your input element:
<input type="submit" name="submit" value="Choose Subject"/>
to something other than "submit". As the .submit() docs state:
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures.
jsFiddle example

Form submit fails the firstime and works upon refreshing the page

I'm running a django web app, when I first submit a form it fails, I need to refresh and submit it again to send the data within, or doing back forward on the web browser.
I'm using a javascript program (editarea) for auto-coloration code on a textarea
Here is my HTML file:
<html>
<head>
<title>Test</title>
<script language="javascript" type="text/javascript" src="/static/edit_area/edit_area_full.js"></script>
<script type="text/javascript">
function load() {
var combo = document.getElementById('selSeaShells1').value;
editAreaLoader.init({
id: "textarea_1" // textarea id
, syntax: combo // syntax to be uses for highgliting
, start_highlight: true // to display with highlight mode on start-up
});
}
</script>
</head>
<body onload="load();">
<form id="codeid" method="post" enctype="application/x-www-form-urlencoded" name="code" action="DestinationAddress/function">
<h3>Choose a language</h3>
<select name="sellang1" id="selSeaShells1" onchange="load();">
<option value="python">Python</option>
<option value="perl">Perl</option>
<option value="sql">SQL</option>
<option value="cpp">C++</option>
<option value="c">C</option>
<option value="java">Java</option>
<option value="css">Css</option>
</select>
<br>
<textarea id="textarea_1" name="content" cols="80" rows="15" type="text"></textarea>
<input id="thebutton" type="button" value="Submit" onclick="document.forms.codeid.submit();" />
</form>
</body>
</html>
and here the views.py:
def function(request):
encoded_data = urllib.urlencode(request.POST)
url=urllib2.urlopen('http://webappAddress:8000/function/?' + encoded_data)
tml= url.read()
return HttpResponse(tml)
Your javascript failing.
var combo = document.getElementById('selSeaShells1').value;
Combo is going to be undefined because you are calling load() before the page finishes loading.
I would use jquery and do this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> //download and get a local copy of jquery don't use googles.***<script>
$(document).ready(function() {
load();
});
function load()
{
var combo = $('#selSeaShells1 option:selected).val();
editAreaLoader.init({
id : "textarea_1" // textarea id
,syntax: combo // syntax to be uses for highgliting
,start_highlight: true // to display with highlight mode on start-up
});
}
</script>
Remove onload="load();" on body tag
This will get the selection after the page loads.

How to Get data from Combo Box and Input it to Text Box with Javascript?

I have this code, it is quite simple but why isn't it working?
<html>
<head>
<script type=”text/javascript“>
function Expedisi()
{
var x=document.getElementById("cmb");//this the script for get data combo box
var y = document.getElementById("txt");
getCmb = x.value;
y.value = getCmb;
alert(x);
}
</head>
<body>
<select name="JENIS" id="cmb" data-role="slider" onChange="Expedisi()">
<option value="Suplier">Sup</option>
<option value="Expedisi">Exp</option>//if i pick one of this the value will be input on text box
</select>
<input type="text" name="BKIRIM" id="txt" value=""> //this the destination value
</body>
</html>
Can anyone Helpme? because this script is not run?
Thanks
You don't need getCmb, and you don't need to declare an extra element.
Use this instead:
<html>
<head>
<script type="text/javascript">
function Expedisi(t)
{
var y=document.getElementById("txt");
y.value = t.value;
}
</script>
</head>
<body>
<select name="JENIS" id="cmb" data-role="slider" onChange="Expedisi(this);">
<option value="Suplier">Sup</option>
<option value="Expedisi">Exp</option>
</select>
<input type="text" name="BKIRIM" id="txt" value=""/>
</body>
</html>
Your code is working for me. Try it here. http://jsfiddle.net/DLs7j/
That is the same exact code as yours. Copy, pasted.
Best
You need to change the quotes around the script type tag.
You are current using the ”” instead of ""; so change ”text/javascript” to "text/javascript".

Categories

Resources