Javascript to check for form data does not work - php

I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!

document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.

document.getElementById selects an element by id, not by name.
Some ways to solve the problem:
Add id="requestorfirstname" to the input element.
Use document.getElementsByName('requestorfirstname')[0]. getElementsByName returns a list, hence [0].
Use the document.querySelector('[name="requestorfirstname"]') method.
Get a reference to the form, and access the element using the .elements collection.For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']

A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this

Related

Jquery - How to get current input value from a repeating from

I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.
To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.
You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();
try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)

form validation using javascript in changing input tags

I need to validate a form using JavaScript. The form keep changes since I am using data from a field name table to print each field (like name, address, phone no.). I'm using a loop to print the label for field and corresponding text input tag. (eg. name : textbox to enter name, phone no : textbox to enter phone no.) And at last getting these values in an array when submitting the form and entering into details table.
Following is the code for printing each field and text box:
while ($row=mysql_fetch_array($result)){
echo'<labelfor='.$row['field_name'].'name=field_id>'.$row['field_name'].':</label>';
echo'<inputtype="text" name=field_name[]id="'.$row['field_id'].'":value="'.$row['field_value'].'" size="20" class = "inpBox" >';
}
Now I need to check whether these fields are empty using JavaScript and then change the style of that particular text box. Any help will be greatly appreciated.
You'll want to hook on the submit event for your form. You could then do something like:
This is for jQuery:
$("form").submit(function{
$('input[type="text"]',"form").each(function(){
var $me = $(this);
var status = true;
if($me.val() == ""){
$me.addClass("input-validation-error");
status = false;
}
//Return status. True=Form is valid, False=Form is NOT valid
return status;
});
});
You can read more here: http://api.jquery.com/submit/
To get the values for javascript, you could do something like:
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var me = inputs[i];
if(me.value == "") {
me.className = "input-validation-error";
}
}​
Generally Google "dynamic form validation"
For your particular case you will be interested in
See https://developer.mozilla.org/en/DOM/document.getElementsByClassName
and loop over all elements. You may want to add extra properties to your entry fields to define if it needs validation and the type of validation needed.

Create form dynamically in table

Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>

Determine if empty $_POST submitted

I have a form containing tabular data, with each row having a checkbox with the same name so that it gets passed via POST as an array to a PHP page. Everything work fine, but I have an issue relating to when none of the items on the page are selected - this is a special case that I need to handle in a specific way, but I am trying to figure out how to determine the best way to tell when this condition occurs, as when it does the $_POST array is completely empty.
Any strategies to help in determining when an empty set of data has been POSTed to a page in PHP?
Use the empty function
if( empty($_POST) ) {
//do empty $_POST stuff here
}
Add a hidden input field to the page with a known value. This field will always be passed in with the POST data, therefore you will know that the user landed via form submission rather than direct URL. It's as simple as:-
<input type='hidden' name='posted' value='true'>
You can accomplish this a few different ways.
//Method 1
if($_POST) {
//Do Stuff
}
//Method 2
if(!empty($_POST)) {
//Do Stuff
}
//Method 3 - For detecting if a form was submitted
<input type="submit" name="submit" />
if(sizeof($_POST)>1) {
//Do Stuff
}
Method 2 will fail if your value is 0, for a checkbox you need not worry though.
Method 3 relies on you giving your submit button a name, so it is at least submitted when nothing is checked. Then you can see if sizeof() returns more than 1 to see if anything was checked.
DEMO: http://wecodesign.com/demos/stackoverflow-7424062.php
I think you've answered your own question. If the $_POST array is empty then there are no checked checkboxes.
<form>
<input type="text" name="user" value="" />
<input type="submit" name="post" value="Save" />
</form>
//php
if (isset($_POST['post']))
{
//code here
}
if ( !empty( $_POST["field"] ) ) {
// Field sent
} else {
// Field empty
}
(count($_POST) == 0) //returns boolean
or do you mean when the form is posted but no information is entered?
Post data is available when a form is submitted. Given the following:
if($_POST)
{
// Bar
}
// Foo
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed and then Foo.
Given the following:
if ($_POST)
{
// Bar
}
else
{
// Foo
}
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed.
As for your other question, checking for empty or appropriate data is basic server-side form validation. If you use a library that can be as simple as:
if ($_POST)
{
$form_helper = new FormHelper();
$form_helper->validate($_POST["email"], "email");
$form_helper->validate($_POST["password"], "password");
if (! $form_helper->notifications())
{
// Bar
}
}
For your specific case (and without a library) it might be:
if ($_POST)
{
if (empty($_POST["checklist"])
{
// Delete all entries.
}
else
{
// Do something else.
}
// Foo
}
This will check if any form values have been entered - assuming default input value = ''
$post = array_filter($_POST,'strlen'); //filter all empty values
//if html input submit button has NO name value
if (sizeof($post)):
//Do stuff
endif;
// OR if html input submit button HAS a name value
if (sizeof($post) > 1):
//Do stuff
endif;
You could use a callback function if exact filtering was required
$post = array_filter($_POST,function ($k){ return $k != '' || $k != 'my default value' || *some other condition etc etc* ; });

Code that checks for required text in textboxes upon submit

how can I check if the user filled some textboxes upon submit? My textboxes have different id and name.
If the user did not fill the required like password the form is not continued.
Thank you.
You can do this using JavaScript or within the script itself.
If using javascript, you simply check the form fields against your requirements before allowing the form to submit. However, you may still need to implement this in the script in case ofr some reason they have javascript turned off.
Basically, in the script, you check the values of the form when they submit:
if($_GET['field_name']) !== 'the value I expect') {
// show the form again with errors
}
// continue
Hope that helps.
Try the below. Naturally you can tweak the form and id's and such, but the basic principle should work. also shown here: http://jsfiddle.net/j3nSB/2/
<form>
<input type="text" id="username" value=""/>
<input type="password" id="password" value="" />
<input type="submit" id="submitButt" value="Go" />
</form>
document.getElementById("submitButt").onclick = function () {
if(document.getElementById("username").value.length == 0 |document.getElementById("password").value.length == 0) {
return false;
}
}
Assuming you have one form, here is the most simple/generic way I can think of, using plain JavaScript.
<script type="text/javascript">
var arrRequiredFields = [ "txtPassword", "txtEmail" ];
window.onload = function() {
document.forms[0].onsubmit = function() {
for (var i = 0; i < arrRequiredFields.length; i++) {
var field = document.forms[0].elements[arrRequiredFields[i]];
if (field && field.value.length == 0) {
alert("Missing required value");
field.focus();
return false;
}
}
return true;
};
};
</script>
Just put the names (not ID) of the required elements, put the code in your page and you're all set.
Live test case: http://jsfiddle.net/kf7pL/
use this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Its very easy to use, and you can just add a class of 'required' to each required input field.
its as easy as $('#form').validate();
It also supports things like integer and date. Highly recommend it to anyone

Categories