Can validate an array of date[] but not process it? - php

I have a problem with this now, on the end of my mydate I have put [] so I can have an array to process and on the other page, I have process.php.
In the process.php, I have
foreach($_POST["mydate"] as $mydate ){
if($mydate != ''){
Date processed...etc etc....
}
If I put the [], it will store it but wont validate and if I dont put [], it will validate but not post?
Any thoughts?
<script type="text/javascript">
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
function CheckDates(inputs)
{
var i, len;
if (inputs.length) {
len = inputs.length;
for (i = 0; i < len; i++) {
if (!checkdate(inputs[i])) return false;
}
return true;
}
return checkdate(inputs);
}
function add(tbl1) {
var tbl = document.getElementById(tbl1);
var rowCount = tbl.rows.length;
var row = tbl.insertRow(rowCount);
var colCount = tbl.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newCell = row.insertCell(i);
newCell.innerHTML = tbl.rows[1].cells[i].innerHTML;
}
}
</script>
<form name "enter" action="enter.php" onSubmit="return Checkdate(this.mydate)" method="post">
<table id="day" border="1">
<tr><b>Valid date format:</b><br></tr>
<tr><td>
<input type="text" name="mydate" />
</table><br>
<input type="submit" value="submit" />
<input type="button" value="Add Row" onclick="add('day')"/>
</form>
EDITTED
removed the space but still doesnt work

If there are more than one of the input field, the name must be mydate[] so they are placed in an array, and in your processing code you have an extra space... $_POST['mydate '] won't work it must be $_POST['mydate']
edit: this line <input type="text" name="mydate" /> must be <input type="text" name="mydate[]" />

Try this construction:
foreach ($_POST["mydate"] as $mydate ) {
if(!empty($mydate) && !is_null($mydate)) {
}
}

Related

jQuery live calc multirow input

This is my code:
<?php
for($i=1;$i<10;$i++){
echo '<input type="text" class="count value'. $i .'">';
echo '<input type="text" class="count '. $i .'value">';
echo '<input type="text" disabled="disabled" id="result'. $i .'"><p>';
}
echo '<input type="text" disabled="disabled" id="total"><p>';
?>
and jQuery:
$(document).ready(function(){
$(".count").keyup(function(){
for (var i = 0; i < 10; i++) {
var val1 = +$(".value"+ i).val();
var val2 = +$("."+ i +"value").val();
$("#result" + i).val(val1*val2);
}
});
});
$(document).ready(function(){
$(".count").keyup(function(){
for (var i = 0; i < 10; i++) {
var vala = 0;
vala += +$("#result"+ i).val();
}
$("#total").val(vala);
});
});
First part of code works great.
Return multiplication two inputs to id=result$i.
I have a problem with last one id=total.
It should return sum of all result X inputs
but now only return the last multiplication.
Do You have any idea what's wrong?
You can simplify your code by grouping the related input elements together in a containing div, using DOM traversal to retrieve the needed values, and joining the two for loops together. Try this:
<div class="group">
<input type="text" class="count valueA" />
<input type="text" class="count valueB" />
<input type="text" class="result" disabled="disabled" />
</div>
<!-- repeat the above as needed. Note that the incremental id is no longer needed -->
<p>
<input type="text" disabled="disabled" id="total" />
</p>
$(document).ready(function(){
$(".count").keyup(function() {
var total = 0;
$('.group').each(function() {
var $group = $(this);
var valA = +$group.find('.valueA').val() || 0;
var valB = +$group.find('.valueB').val() || 0;
var result = valA + valB;
total += result;
$group.find('.result').val(result);
});
$("#total").val(total);
});
});
Example fiddle
That is because you have defined variable vala to 0 in for loop. which should be outside for loop:
$(".count").keyup(function(){
var vala= 0;
for (var i = 0; i < 10; i++) {
vala += $("#result"+ i).val();
}
$("#total").val(vala);
});

jquery validations are not working when i click on submit button

I have written a html form and jquery to perform the validations. But when i click the submit button, nothing is happening. I can't understand what is going on, whether the form is linking up with the jquery file or not. Please any check my code and help me.
index.html
<html>
<head>
<title>validation</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
</head>
<body>
<form action="" method="post" id="reg_form">
<p>Name:</p>
<p><input id="name" name="name" type="text"></p>
<p>What's your name?</p>
<p>Email:</p>
<p><input id="email" name="email" type="text"></p>
<p>Enter mail id</p>
<p>Password:</p>
<p><input id="pass1" name="pass1" type="password"></p>
<p>More than 8 characters</p>
<p>Password:</p>
<p><input id="pass2" name="pass2" type="password"></p>
<p>same as above</p>
<p>phone</p>
<p><input id="phone" name="phone" type="text"></p>
<p>What's your number?</p>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
</body>
</html>
custom.js
$(document).ready(function(){
var form = $("#reg_form");
var name = $("#name");
var nameDetails = $("#nameDetails");
var email = $("#email");
var emailDetails = $("#emailDetails");
var pass1 = $("#pass1");
var pass2 = $("#pass2");
var pass1Details = $("#pass1Details");
var pass2Details = $("#pass2Details");
var phone = $("#phone");
var phoneDetails = $("#phoneDetails");
var button = $("#submit");
name.blur(validateName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
phone.blur(validatePhone);
name.keyup(validateName);
email.keyup(validateEmail);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
phone.keyup(validatePhone);
form.submit(function(){
if(validateName() & validateEmail & validatePass1 & validatePass2() & validatePhone()){
return true;
}else{
return false;
}
});
function validateName(){
if(name.val().length<5){
name.addClass("error");
nameDetails.text("Your name should have atleast 5 characters");
nameInfo.addClass("error");
return false;
}else{
name.removeClass("error");
nameDetails.text("Whats your name?");
}
}
function validateEmail(){
var a = $("#email").val();
var regexp = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-za-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.text(a)){
email.removeClass("error");
emailDetails.text("Enter mail id");
emailDetails.removeClass("error");
return true;
}else{
email.addClass("error");
emailDetails.text("Enter valid mail id");
emailDetails.addClass("error");
}
}
function validatePass1(){
if(pass1.val().length<8){
pass1.addClass("error");
pass1Details.text("8 characters or more");
pass1Details.addClass("error");
return false;
}else{
pass1.removeClass("error");
pass1.Details.text("Enter mail id");
pass1.Details.removeClass("error");
return true;
}
}
function validatePass2(){
if(pass2.val().length < 1){
pass2.addClass("error");
pass2Details.text("8 characters or more");
pass2Details.addClass("error");
return false;
}
if(pass1.val()!== pass2.val()){
pass2.addClass("error");
pass2Details.text("8 characters or more");
pass2Details.addClass("error");
return false;
}else{
pass2.removeClass("error");
pass2.Details.text("Same as above");
pass2.Details.removeClass("error");
return true;
}
}
function validatePhone(){
var b = $("#phone").val();
var regexp = /[0-9]{10}/;
if(filter.text(b)){
email.removeClass("error");
emailDetails.text("Enter phone number");
emailDetails.removeClass("error");
return true;
}else{
email.addClass("error");
emailDetails.text("Enter valid phone number");
emailDetails.addClass("error");
}
}
});
use the statements like this,
var name = $("#name ").val();
Or
var name = jQuery("#name ").val();
and then try...it will work...
Try this
$(document).ready(function(){
var form = $("#reg_form").val();
var name = $("#name").val();
...
});
Try this..
$(document).ready(function(){
var name = $("#name").val();
var nameDetails = $("#nameDetails").val();
var email = $("#email").val();
var emailDetails = $("#emailDetails").val();
var pass1 = $("#pass1").val();
var pass2 = $("#pass2").val();
var pass1Details = $("#pass1Details").val();
var pass2Details = $("#pass2Details").val();
var phone = $("#phone").val();
var phoneDetails = $("#phoneDetails").val();
});

How to detect if two input elements like text fields are typed in. (php/javascript)

If two input elements in a form - for example - text fields, lets say username and password, get text input with length > 0, how would you create an event to change a submit button color the moment the user has typed in both fields?
document.getElementById('submit').onclick = function() {
var inputs = document.getElementsByTagName('input'),
empty = 0;
for (var i = 0, len = inputs.length - 1; i < len; i++) {
empty += !inputs[i].value;
}
if (empty == 0) {
//write code for changing the button color
}
};
I like the answer above, and here is a jquery answer if you like the looks better!
$(document).ready(function() {
$("#username").change(checkFunction());
$("#password").change(checkFunction());
}
function checkFunction() {
var user = $("#username").val();
var pass = $("#password").val();
if (user && pass) {
$("#buttonid").css("background-color:#HEXCODE");
}
}
Make a javascript function that checks if both inputs have a value greater than zero and if they do it changes the color of the submit button when called.
Use the onChange attribute in the input tag and place the name of the javascript function in the attribute.
You can also set the attribute by doing
Object.onChange = functionToCall();
onChange fires the function it's set to whenever the input value changes.
If you have Jquery in your project, you can try something like this:
Assuming your inputs have ids:
<input id="username" name="username"/>
<input id="password" name="password"/>
<input type="submit" value="Submit" id="submit" />
You can bind to the keyup event on either input element to change the color of the button:
$('#username, #password').keyup(function(){
if ($.trim($('#username').val()) != '' && $.trim($('#password').val()) != '') {
$('#submit').css('background-color', 'red');
}
});
Here is the running fiddle:
http://jsfiddle.net/NS5z6/
HTML:
<input type=text id=username />
<input type=password id=password />
<input type=submit id=submit />
CSS:
#submit{ background-color: red; }
JS:
$('input[id="username"], input[id="password"]').change(function(){
if ($(this).val()!="")
{
$("input[id='submit']").css("background-color","green");
}else{
$("input[id='submit']").css("background-color","red");
}
});
You can use following logic
<input type = "text" name = "username" class = "text">
<input type = "password" name = "password" class = "text">
<input type = "button" class = "button">
<script>
$(".text").live("keyup", function(){
var filled = true;
$(".text").each(function(i, v){
if($(this).val() == ''){
filled = false
}
});
if(filled){
$(".button").css("background-color:#black");
}
});
</script>

Getting NaN from form PHP form using JS

I'm getting a NaN value if i try to do any math with the two vars i pull form the form. It also gives me NaN if i try it parseInt it. IDK if it helps but the values are pulled from the URL using PHP; example: .../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=5&limiterT=20
limiterF and limiterT are the vars I'm working with.
html:
<form id='serchForm' action="serch.php" method="GET">
...
<fieldset>
From: <input type='text' id = 'limiterFid' name='limiterF' value=<?php if (!empty($_GET['limiterF'])) {echo $limiterF;} else {echo 0;} ?> size="2" /><br />
To: <input type='text' id = 'limiterTid' name='limiterT' value=<?php if (!empty($_GET['limiterT'])) {echo $limiterT;} else {echo 20;} ?> size="2" />
</fieldset>
<input type="submit" id="submitNew" />
<input type="submit" id="nextSerch" />
JS:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').attr("value", 0);
$('#limiterTid').attr("value", 20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').value,
limiterT = $('#limiterTid').value;
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').attr("value", limiterF);
$('#limiterTid').attr("value", limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});
This is what it will return when you click nextSerch:
.../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=NaN&limiterT=NaN
value is a property of the DOM element not the jQuery object. You can use either val() or value on the original DOM element.
$('element').val()
// OR
$('element')[0].value
Also to set values you typically don't use attr, you use val.
$('element').val('newValue')
Use the .val() method, as value will returned undefined as it is attempting to call the 'value' property of a jQuery object:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').val(0);
$('#limiterTid').val(20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').val(),
limiterT = $('#limiterTid').val();
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').val(limiterF);
$('#limiterTid').val(limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});

Adding multiple rows to database from dynamic field event

I have a dynamic event in JS in my form which adds another block of fields so my users can add another address:
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id',
'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*11 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
if (newNum == 3) $('#btnAdd').attr('disabled', 'disabled');
});
$('#btnDel').click(function() {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
</script>
However, when I put my form action the page just refreshes when I click my 'add another address' button:
<form action="address.php" method="post" name="regForm" id="regForm" >
These are my fields:
if(empty($err)) {
for($i = 0; $i < 10; $i++)
{
$Street = $_POST['Street'][$i];
$Line2 = $_POST['Line2'][$i];
$Line3 = $_POST['Line3'][$i];
$Town = $_POST['Town'][$i];
$Postcode = $_POST['Postcode'][$i];
$Country = $_POST['Country'][$i];
$Tele = $_POST['Tele'][$i];
$Fax = $_POST['Fax'][$i];
$Type = $_POST['Type'][$i];
$Mobile = $_POST['Mobile'][$i];
$sql_insert = "INSERT into `address`
(`Street`,`Line2`,`Line3`,`Town`, `Postcode` ,`Country`,`Tele`,`Fax`,`Type`
,`Mobile` )
VALUES
('$Street','$Line2','$Line3','$Town','$Postcode','$Country',
'$Tele','$Fax','$Type', '$Mobile'
)";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
I want all addresses to go to mysql database.
I hope this is clear
Define buttons as followed: <input type="button" value="ButtonLabel" />.
My short test resulted in my <button> getting treated as submit type input by firefox. This means <button>FooBar</button> and <input type="submit" value="FooBar" /> are equivalent.
You might also want to simplify your javascript code. You can use the array notation for input names:
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
will result in $_POST["street"][0] and $_POST["street"][1] beeing filled with the user's input. This is what you want judging from your php code, anyway.
You don't need ids for all your input tags. Just keep one full set of inputs for one address and append this to your form. Maybe something like:
$('#address').append(
'<div>' +
'<input type="text" name="street[]" />' +
'<input type="text" name="zip[]" />' +
'</div>'
);
Or just have a full set hidden on your page and clone it, then append. I'm sure our jQuery pros will know a better solution.
And finally: Please sanatize your input with mysql_real_escape_string
$Street = mysql_real_escape_string($_POST['Street'][$i]);
// and so on for the other values.

Categories