JS validation troubles and some more gimmicks - javascript

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>

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;
}

Simple Javascript Validation not working

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.

Is it possible to construct a link, navigate to it and print the response in C# programmatically? How?

I have a webpage written in C#/Razor. I am printing all the values from a database on this page like so :
<div style="min-height: 150px; font-size: 1.25em">
<div style="margin-bottom: .5em">
<table>
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Phone No.</th>
<th>Extension</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var prod in Model)
{
<tr>
<td>#prod.FullName</td>
<td>#prod.Branch</td>
<td>#prod.PhoneNo</td>
<td>#prod.Extension</td>
<td>#prod.Email</td>
#if (User.IsInRole(#"Admins") || User.Identity.Name == prod.DomainAC)
{
<td>edit</td>
}
else
{
<td>User => #User.ToString()</td>
}
<td>
<input type="checkbox" name="message" value="#prod.PhoneNo">Message<br>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
This works fine to display their info. What I would like to do now is a small bit more difficult.
Below this, I have a form with a username, password and message. Using this form, I would like to have the behaviour that on submit, it will take the values in the input boxes of the form and the above C#, construct a link, navigate to the link and print the response of the server
So I have :
#{if (IsPost)
{
//handle and print response
}
else
{
<form method="post" action="">
Username:<br />
<input type="text" name="u" /><br />
Password<br />
<input type="text" name="p" /><br />
<br />
Password<br />
<textarea name="m" cols="25" rows="5">
Enter your comments here...
</textarea><br>
<br />
<input type="submit" value="Submit" class="submit" />//when this is clicked, construct url and navigate to it.
</form>
}
}
The URL I want to construct from this form is :
http://webaddress.com/web/d.php?u=<Username entered by user>&p=<Password entered by user>&s=<List of Phone Numbers from the C# above where the checkbox is selected, comma separated>&m=<Comment submitted by user>
So, if my name is "John", Password is "Password1", Comment is "Test" and I have selected one checkbox for a user with the phone number "12345678", the URL I will navigate to is :
http://webaddress.com/web/d.php?u=John&p=Password1&s=12345678&m=Test
Ideally I would like to print the response of the webpage in a <div> while still on the same parent web page rather than going to a new one if this is possible.
I have no idea where to begin with this, how to do it or even if this is possible. Can anyone help me please ?
UPDATE :
Trying this JQuery which does not alert me so I cannot debug :
<script>
$("#thebutton").click(function() {
var form = $(document.getElementById('FormID'));
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#u').val();
urlToConstruct += '&p=' + form.find('#p').val();
('#employeeTable tbody tr').has(':checkbox:checked').find('td:eq(2)').each(function() {
urlToConstruct.append($(this).text());
alert(urlToConstruct);
})
});
</script>
$("#SubmitButtonID").click(function() {
var form = $(document.getElementById('FormID');
var urlToConstruct = 'http://webaddress.com/web/d.php';
urlToConstruct += '?u=' + form.find('#iDoFInputControl1').val();
urlToConstruct += '&p=' + form.find('#iDoFInputControl2').val();
form.submit();
});
this example uses jQuery, a javascript library (jquery.com), i'm using getElementById to find your form, faster then the native jQuery() selector. This example assumes all your controls are inside your form (but if they are not it wouldn't be a train smash, just cant use (jQuery obj).find).
.val() gets the value, and it should work for checkboxes too, but if it doesn't, a quick google search for getting values from checkboxes using jquery will return loads of results.
p.s. I've written that code mostly freehand, not checked it in a browser to make sure that it is completely correct.
Update... to answer your follow up question...
If you are using mvc (assumed as you using razor), inside your controller you can use Request.Params["urlParameter"] or Request.Form["controlID"] to access what you've received from the browser. Then once you've got those values, you should place them inside the 'ViewBag' (ViewBag.yourVariableHere="val") for them to be accessible in your view via #ViewBag.yourVariableHere, or you can include the required data in your model which can also be accessed in your view

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