Simple Javascript Validation not working - javascript

I am trying to do the following:
HTML Code
<body>
<form name="myform">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" id="first_name"></td>
<td><p id="demo"></p></td>
</tr>
<tr>
<td><input type="submit" id="Submit" onclick="validate()"></td>
</tr>
</form></body>
JavaScript Code
<script>
function validate(){
var fname = document.getElementById("first_name").value;
if(fname.length>0){
document.getElementById("demo").value="";
}
else{
document.getElementById("demo").value="Name field empty";
}
}
</script>
when I click the button with the empty First name field it should assign "name field empty" but it does not do that even though the control of the script goes there but it does not print anything in the <p> tag.

I think you should try this instead :D
<script>
function validate(){
var fname = document.getElementById("first_name").value;
if(fname!=""){
document.getElementById("demo").innerHTML="";
}
else{
document.getElementById("demo").innerHTML="Name field empty";
}
}
</script>
You wanna check if the field is empty or not so in this case the fname is enough to use all along. If the variable fname (which is the first_name field's value) is not empty then it proceed the statement that will set the HTML content of "demo" to "" with .innerHTML. The .value you used has nothing to do with the display HTML content relating to demo :D. I hope my English is not that bad for you to understand this.

Related

HTML form javascript to associate question, answer and feedback

I have a language quiz in an HTML form When the user checks their entry, feedback is inserted into cell in the form of a tick or cross icon . My problem is that the feedback is always inserted into the first td whether the first or second question is answered and checked. Question and appropriate answer are associated with elementNo: I can't figure out how to associate the "mark" cell with the its answer and question
<SCRIPT>
//Define the answers.
Answer = new Array( "Die Maus ist weiss.", "",
"Auf Wiedersehen!");
//inserts icon, however only in the first element named "mark".
// Somehow needs to select correct place according to element number
function itemfeedback (elementNo)
{
if (document.E1a.elements[elementNo].value == "")
{
alert("You must type an answer!");
}
else if (document.E1a.elements[elementNo].value == Answer[elementNo])
{
document.getElementById("mark").innerHTML = "<img src='correct.jpg'>";
}
else
{
document.getElementById("mark").innerHTML = "<img src='incorrect.jpg'>";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="E1a" accept-charset="ISO-8859-1" onReset="return confirm('Clear entries? Are you sure?')">
<HR>
<H3>
translate, remembering punctuation and capitalisation...
</H3>
<table>
<tr>
<td>1. The mouse is white.</td>
<td><INPUT TYPE="TEXT" NAME="Q1" SIZE=50 MAXLENGTH=50></td>
<td><INPUT TYPE="button" id ="check_button" VALUE="check..." NAME="B1" onClick="itemfeedback(0)"></td>
<td id="mark"></td>
</tr>
<tr>
<td>2. Good-bye!</td>
<td><INPUT TYPE="TEXT" NAME="Q2" SIZE=50 MAXLENGTH=50></td>
<td><INPUT TYPE="button"id ="check_button" VALUE="check..." NAME="B2" onClick="itemfeedback(2)"></td>
<td id="mark"></td>
</tr>
</table>
<hr>
<INPUT TYPE="RESET" id ="reset_fields" VALUE="Clear Entries">
</CENTER>
</FORM>
</BODY>
</HTML>
I hope that my question is clear and that someone will help.
Quick Answer
ID's are intended to be unique within a HTML document according to HTML5 specs. Because of this, all instances of an ID after the first occurrence are ignored by JavaScripts "getElementById" function. A more proper way to select multiple DOM elements is to use the "class" attribute, like this:
<td class="mark"></td>
...
<td class="mark"></td>
And reference it using JavaScript, using "getElementsByClassName"
document.getElementsByClassName('mark')
More Helpful Answer
I would make a couple more suggestions, to make your code a bit more dynamic, and functional. I have inserted comments in the code below to explain the changes/suggestions I have.
<html>
<head>
<script>
// We will use an object instead of an array, so that we can reference the answers by a string, rather then an integer.
// Also, any time a NEW variable is defined, it should be prefaced with "let" or "const" for >= ES2015, or "var" for < ES2015 (see https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c for details on the different script versions)
const answer = {
Q1: "Die Maus ist weiss.",
Q2: "Auf Wiedersehen!"
};
// itemfeedback function is now passing the input id, rather than the index
function itemfeedback (id) {
// This will get the input, associated with the button
let input = document.getElementById(id),
// This will be the ID of the mark element that is associated with the submitted input
markId = "mark" + id,
// This is the mark element assocaited with the submitted input
mark = document.getElementById(markId);
if (input.value == "") {
alert("You must type an answer!");
}
// Since we have assigned the answers to an object, and gave each of the answers indexes to match the input ids, we can find the answer by that
else if (input.value == answer[id]){
mark.innerHTML = "<img src='correct.jpg'>";
} else {
mark.innerHTML = "<img src='incorrect.jpg'>";
}
}
</script>
</head>
<body>
<form NAME="E1a" accept-charset="ISO-8859-1" onReset="return confirm('Clear entries? Are you sure?')">
<HR>
<H3>
translate, remembering punctuation and capitalisation...
</H3>
<table>
<tr>
<td>1. The mouse is white.</td>
<!-- Gave input ID of "Q1" -->
<td><input TYPE="TEXT" NAME="Q1" SIZE=50 MAXLENGTH=50 id="Q1"></td>
<!-- Changed id to class, since it is non-unique -->
<td><input TYPE="button" class="check_button" value="check..." NAME="B1" onClick="itemfeedback('Q1')"></td>
<!-- We will give this an ID that can be associated with it's related inputs name attribute -->
<td id="markQ1"></td>
</tr>
<tr>
<td>2. Good-bye!</td>
<!-- Gave input ID of "Q2" -->
<td><input TYPE="TEXT" NAME="Q2" SIZE=50 MAXLENGTH=50 id="Q2"></td>
<!-- Passed ID to onChange handler, instead of index. Also hanged id to class, since it is non-unique -->
<td><input TYPE="button" class="check_button" value="check..." NAME="B2" onClick="itemfeedback('Q2')"></td>
<!-- We will give this an ID that can be associated with it's related inputs name attribute -->
<td id="markQ2"></td>
</tr>
</table>
<hr>
<input TYPE="RESET" id="reset_fields" value="Clear Entries">
</center>
</form>
</body>
</html>
EDIT for Form Reset
Place this function to remove images from form onReset:
<!-- We are now calling a function to be executed, and the returned value of the function will determine if the form itself is cleared. A negative blue will not, a positive value will -->
<form NAME="E1a" accept-charset="ISO-8859-1" onReset="return clearForm(this)">
function clearForm (form) {
// Get option that is pressed
var clear = confirm('Clear entries? Are you sure?');
// If positive option is clicked, the form will be reset
if (clear) {
// This will select all images within the document
var markImgs = document.getElementsByTagName('img');
// Iterates through each image, and removes it from the dom
while (markImgs[0]) markImgs[0].parentNode.removeChild(markImgs[0])
}
return clear;
}

Appear a textbox only when the checkbox is checked and not save the field in the database if is not checked

Sorry for english grammar, not my native language.
I want to show a textbox only when the checkbox is checked. So, i have this code:
HTML
<table>
<tr>
<td>
<input type = "checkbox" id="NCFtxt" onclick="obtenerNCF()"> Marcar casilla para generar Comprobante Fiscal
</td>
</tr>
<tr>
<td>
NCF: <input readonly="readonly" name= "txtNCF" type= "text" id= "txtNCF" value= "<?php echo $cobro->ncf; echo $ncf; ?>" />
</td>
</tr>
</table>
JAVASCRIPT
<script language="javascript">
$("#txtNCF").hide();
function obtenerNCF() {
var chequear = document.getElementById("NCFtxt");
if (chequear.checked == true){
$("#txtNCF").show();
} else {
$("#txtNCF").hide();
}
}
</script>
So, this is "working", is hiding the field when the checkbox is checked, but still saving the data at the Database. How can I do to not only hide the field, but neither saved in the database? I was trying some things but none worked, this seems simple, but it confusing me
If you don't want to save something based on a checkbox... look at the $_POST if the checkbox has a value or not (if not, then it was not checked). Then save or not-save the extra data.
Give the checkbox a name and value:
<input type="checkbox" name="NCFtxt_checkbox" value="1" id="NCFtxt" onclick="obtenerNCF()">
And in PHP look for it:
if ( empty($_POST['NCFtxt_checkbox']) ) {
// dont save extra data
} else {
// else do save the extra data
}
A second solution is to use a lot of javascript, and when the checkbox is UN-checked, you clear-out the content of the other text box as you hide it. That way it would be submitted 'emtpy' to begin with.

JS validation troubles and some more gimmicks

I've already have validated my form using php but I would like to change it to use javascript.For some reason it doesn't seem to work, and I cannot understand why.
<form name="adminFormNewMember" method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter()" required autofocus></td>
</tr>
</table>
</form>
---------------------
<script>
function allLetter()
{
var text = document.getElementById("firstname");
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
Obviously the form contains more stuff, I've omitted them for the sake of clarity.
Also I'd like to use the same function for more field such as lastname etc, but I don't know how to do that since I'm using the getElementById
Finally, I'd like to just highlight the textfield red for errors, green for correct etc.
Clarification Edit I still need the PHP part I just don't want it to validate. I need the validation to happen for each field onBlur, and then the data to be passed to the php function to be inserted in a DB etc.
Try this :
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<form name="adminFormNewMember" method="post" >
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter(this.id)" required autofocus></td>
</tr>
</table>
</form>
<script>
var allLetter = function(id){
var text = document.getElementById(id).value;
if(text.length ==0 || text.toUpperCase().replace(/[^A-Z]/g, "").length != text.length) alert("Incorrect value")
}
</script>
</body>
</html>
To use your function with several fields, just pass the id as a parameter (this.id), in allLetters function, pass the parameter to getElementById.
It seems your Regexp is not correct (or suffiscient), so first check the field is not empty then check if length of value equals lenngth of value with letters only. If so the field is correct, otherwise go for the alert.
Maybe you should consider using jquery and the validate plugin here witch can save you lot of time
Returning true or false in your sample code is achieving nothing. What you need to do is, depending on whether validation is successful or not, add a CSS class to your input field. This CSS class should handle either background or border for your field to indicate that it did not match the criteria.
Instead of using onblur attribute, create an event listener for the blur event on your form fields. Delegate this listener to transfer control to a function which will take the value inside the event target and validate it. This should make your code more modular and apply to most fields.
Here is some code in basic javascript:
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" class="formFields"></td>
<td>Last Name </td>
<td><input type="text" id="lastname" class="formFields"></td>
<td>Fathers Name</td>
<td><input type="text" id="fathername" class="formFields"></td>
</tr>
<script>
for(var i=0; i < document.getElementsByClassName("formFields").length ; i++){
document.getElementsByClassName("formFields")[i].addEventListener("blur", function(evt){
var text = evt.target;
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
evt.target.classList.remove('incorrectField');
evt.target.classList.add('correctField');
}
else
{
evt.target.classList.add('incorrectField');
evt.target.classList.remove('correctField');
}
});
}
<style>
.incorrectField{
background: red;
}
.correctField{
background: green;
}
</style>

how to identify submit() that arrived from javascript method(not button) in asp.net

I have a list of users that in the end of each line in the table I added two links("href"):
one for "update" user and secend for "delete" user.
So for enable that I added a call to javascript function that capture the ID of user
and insert it to some form that I created before (form with only one "hidden" field),
and then the function activated submit() operation to the server part (asp.net code).
I checked and the submit() operation works ok(checked with respons.write()...)
But I know how to recognize a submit form button inside IsPost by ask what the value
of the submit button (for example: if(Request.Form["ExpertButton"]== "delete"){..some code here....})
But when I activate submit() with javascript, how could I recognize post?
I tryed with the value of the hiiden field but it's not capture this
and it skiped of the if statement....
the list of users code:
foreach(var row in db.Query(displayExperts,nameOfExpert))
{
<tr>
<td class="dispExpertActScreen">#row.ExpertID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.password</td>
<td class="dispExpertActScreen">#row.allowBonds</td>
<td class="dispExpertActScreen">#row.allowStocks</td>
<td class="dispExpertActScreen">#row.allowExchangeTraded</td>
<td class="dispExpertActScreen">#row.allowMutualFund</td>
<td class="dispExpertActScreen">update</td>
<td class="dispExpertActScreen">delete</td>
</tr>
}
the form code:
<form method="post" name="deleteExpert" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="expertID" id="expertID" value="">
</form>
the javascript code:
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('deleteExpert').submit ();
}
</script>
the asp.net code:
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayExperts="";
var nameOfExpert="";
var category="";
if(IsPost)
{
if(Request.Form["ExpertButton"]== "search")// this is by button!!!
{
some code.....
}
//Response.Write("^^^^^^^^^^^^^^^^^^^^^");
if(Request.Form["ExpertButton"] != "")// this need to be by javascript submit() method !!! here I need to recognize it.
{
var id=Request.Form["expertID"];
Response.Write("^^^^^^^^^^^^^^^^^^^^^"+id);
var deleteQuery="DELETE FROM InvestmanExperts WHERE ExpertID=#0";
db.Execute(deleteQuery,id);
}
}
db.Close();
}
thanks...
Why not puting another hidden input value :
<input type="hidden" name="txtJavascriptMode" id="txtJavascriptMode" value="">
then in your javascript code :
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('txtJavascriptMode').value = 'true';
document.getElementById('deleteExpert').submit ();
}
</script>
and in your serverside you can checkout
if(Request["txtJavascriptMode"] == "true")
{}

equivalent for request.getParameterValues() in javascript

For example in form, I've 2 or more element that have the same name like in the below code:
<form name="form1" method="post" action="saveToDb.jsp">
<span id="feedBackList">
<table>
<thead>
<tr>
<td>column1</td>
<td>column2</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type=text id=field1 name=field value="firstvalueTosavetoDb"></td>
<td><input type text id="field2 name=field value="secondvalueTosavetoDb"></td>
</tr>
</tbody>
</table>
</span>
</form>
Value for this two field I want to capture and save it to database. This can be done by submit the form, and in my saveToDb.jsp file I just need to get the value by using
String[] value = request.getParameterValues("field");
loop through the array and save it to database. the problem is I don't want to submit the form because the page will be refresh. what I'm trying to achieved is, I want to use jQuery.get method and pass the value and view back the value without refresh the page and put it in my <span> tag like below code
var $p = jQuery.noConflict(){
function submitAndView(){
//here is where i should get the value
var span = document.getElementById("feedBackList");
$p.get("saveToDb",{pass the value here}, function(data){
span.innerHTML = data
});
}
the question is what is the equivalent to request.getParameterValues in JavaScipt or jQuery. p/s: the number of <input> elements is not fixed.
Could you add a name and onsubmit attribute to your form, calling a validation JS function which loops through all of the fields with the same name and constructs some type of string or array for you to easily add info to your db? e.g.:
<form name=form1 action='#' method=post onsubmit='return validateForm()'>
<fieldset>
<input type=text name='field[]' value='firstValue'>
</fieldset>
</form>
function validateForm(){
count = 0;
str = '';
for(x=0; x<document.form1.elements["field[]"].length; x++){
str += document.form1.elements["field[]"][x].value + ','
count++;
}
//submit form data

Categories