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
Related
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>
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.
I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}
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
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")
{}