I'm trying (without success :/ ) to do a form validation to the "name" & "description" fields in a table before clicking the button (a live validation).
I mean, the button "submit" wont do anything before everything it's correct.
Name allows 50 characters only, and cannot be empty (if empty or higher than 50 a red alert should appear)
Description does not allow numbers and only 255 characters (if you insert a number or higher than 255 an alert should appear)
Here is my code, i tried so hard and i donĀ“t know what to do.
<?php include('connect.php');
$error="";
if(isset($_GET['editar']))
{
$ident=$_GET['iden'];
$row=mysql_query("SELECT * FROM subjects WHERE id=$ident");
$st_row=mysql_fetch_array($row);
}
$sqlm = mysql_query("SELECT * FROM careers");
$options = "";
while($resultado = mysql_fetch_array($sqlm)){
$options .= "<option value='".$resultado['id']."'>".$resultado['nombre']."</option>";
}
?>
<h2 align="center">UPDATE SUBJECTS</h2>
<form method="Post" action=''>
<table align="center">
<tr>
<td>Career:</td>
<td><select name='txtcarreras_id'><?php echo $options; ?></td>
</tr>
<tr>
<td>Name:</td>
<td><input type='text' class="form-text" id="form-name" name='txtnombre' value="<?PHP echo $st_row['nombre'] ?>"/><span class="error-form" id="error-name"></td>
</tr>
<tr>
<td>Description:</td>
<td><input type='text' class="form-text" id="form-description" name='txtdescripcion' value="<?PHP echo $st_row['descripcion'] ?>"/><span class="error-form" id="error-description"></td>
</tr>
<tr>
<td>Hours:</td>
<td>
<select name='txtcarga_horaria'/>
<option <?php if($carga_horaria=='1') echo 'selected' ; ?> value="2">2 (dos)</option>
<option <?php if($carga_horaria=='1') echo 'selected' ; ?> value="4">4 (cuatro)</option>
<option <?php if($carga_horaria=='1') echo 'selected' ; ?> value="6">6 (seis)</option>
<option <?php if($carga_horaria=='1') echo 'selected' ; ?> value="8">8 (ocho)</option>
<option <?php if($carga_horaria=='1') echo 'selected' ; ?> value="10">10 (diez)</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type='submit' value="save" name='btnsave'/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['btnsave']))
{
$carreras_id=$_POST['txtcarreras_id'];
$nombre=$_POST['txtnombre'];
$descripcion=$_POST['txtdescripcion'];
$carga_horaria=$_POST['txtcarga_horaria'];
$a_sql=mysql_query("UPDATE subjects SET carrera_id='$career_id', name='$nombre', description='$descripcion', hours='$carga_horaria' WHERE id='$ident'");
if($a_sql)
{
header("location:index.php");//
}
}
?>
<script>
function lettersonly(input){
var regex = /[^a-z]/gi;
input.value = input.value.replace(regex, "");
}
</script>
<script>
$(function()){
$("#error-name").hide();
// $("#error-description").hide();
var error_name = false;
// var error_description= false;
$("#form-name").focusout(function() {
check_name();
});
function check_name(){
var nombre_length = $("#form_name").val().length;
if(nombre_length > 50)
{
$("#error-name").html("NO DEBE SUPERAR LOS 50 CARACTERES");
$("#error-name").show();
error_name = true;
}else {
$("#error-name").hide();
}
}
</script>
<script>
$(document).ready(function(){
$("#inputtext").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
$("#lastname").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
$("#middlename").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
});
$("#age").keypress(function(event){
var inputValue = event.which;
// allow letters and whitespaces only.
if( (inputValue >=65 && inputValue <=123 ) && (inputValue >=32 && inputValue <=47 )) {
event.preventDefault();
}
else if((inputValue >=32 && inputValue <=47 ))
{
event.preventDefault();
}
else if((inputValue >=91 && inputValue <=96 ))
{
event.preventDefault();
}
else if((inputValue >=123 && inputValue <=127 ))
{
event.preventDefault();
}
else if(inputValue < 1 && inputValue >100)
{
alert("the age must be a number between 1 and 100");
return false;
}
else if(inputValue >=92 && inputValue <=123 )
{
event.preventDefault();
}
});
$("#txtct").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
</script>
Just set div id and add masg in this code like
var masg='only number';
$('#divid').html(masg);
Related
I have tried passing value on 3rd drop down but it doenst receive any of it
it doesnt show error but it doesnt get any data from 2 dropdowns Im new to just and im trying something but it doesnt work at all pls help thank you very much
dropdown.php
<select class="form-control" style="font-size: 21px;" name="Building" id="Building" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from Building");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Building']; ?>"><?php echo $row['Building'];?></option>
<?php
}
?>
</select>
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from floor");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Floor']; ?>"><?php echo $row['Floor'];?></option>
<?php
}
?>
</select>
<div id="Dept"></div>
</div>
</div>
<script type="text/javascript ">
function change_floor(str,str1) {
if (str.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "deptajax.php?q="+str+"&d="+str1, true);
xmlhttp.send();
}
}
</script>
deptajax.php
If I use request here i shows error but if I use GET i doesnt show any error what is more usable for this scenario?
<?php
$link=mysqli_connect("localhost","id5592115_retep","Password");
mysqli_select_db($link,"id5592115_admin");
$q = $_REQUEST["q"];
$d = $_REQUEST["d"];
$res=mysqli_query($link,"select * from depttable where Flr='$d' and
Building='$q' order by deptname asc");
echo "<form method='get' action='table2.php'>";
echo '
<select class="form-control" style="font-size: 21px;" name="dept">
';
while ($row=mysqli_fetch_array($res)) {
$deptid = $row['deptid'];
$deptname = $row['deptname'];
echo "<option value='".$deptname."'>".$deptname."</option>";
}
echo "</select>";
echo '<button type="submit" class="btn btn-light
btnmove">Submit</button>';
echo "</form>";
?>
Your onclick function is call every time you select any of the dropdown , so at a time only one value is passed i.e : either str or str1 will have value . Instead to avoid this you can do like below :
When first selectbox is selected try to store it value in some variable like below :
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor"
onChange="change_floor1(this.value)">
<!--^ make another function with name change_floor1-->
<option>Select</option>
...
</select>
Then in your <script></script>do like below :
var s; // declare globally
function change_floor1(str) {
s=str; //assigning value of first-select box in "s"
}
function change_floor(str1) {
if (str1.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
//passing both value
xmlhttp.open("GET", "deptajax.php?q="+s+"&d="+str1, true);
xmlhttp.send();
}
}
<input type="button" value="addkid " onClick="show()" />
<div>
<div id="myTableData" style="display:none; width:800px; height:500px; background-color:yellow; margin:0 auto;">
<form action="javascript:insert()" method="get">
<table>
<tr>
<td width="175">NAME</td>
<td width="245"> Gender</td>
<td width="245">Date of Birth</td>
</tr>
<tr>
<td width="175">
<input type="text" name="kid_name" id="kid_name" />
</td>
<td width="245">FEMALE
<input type="radio" name="gender" value="female" id="gender" />MALE
<input type="radio" name="gender" id="gender" value="male" />
</td>
<td width="245">
<?php for ( $i=1; $i<13; $i++ ) { $month=d ate( 'm', mktime(0,0,0,$i,2,2000)); $sel=( $i==d ate( 'n') ? ' selected="selected"' : ''); $options1[]="<option value=\" {$month}\ " {$sel}>{$month}</option>"; } $options_list1=j oin( "", $options1); echo "<select name=\"month\ " id='month' >{$options_list1}</select>"; for ( $j=1; $j<32; $j++ ) { $theday=d ate( 'd', mktime(0,0,0,0,$j,2000)); $sel=( $j==d ate( 'd') ? ' selected="selected"' : ''); $options2[]="<option value=\" {$theday}\ " {$sel}>{$theday}</option>"; } $options_list2=j oin( "\r\n", $options2); echo "<select name=\"day\ " id='day' >{$options_list2}</select>"; for ( $k=1960; $k<2016; $k++ ) { $theyear=d ate( 'Y', mktime(0,0,0,1,1,$k)); $sel1=( $k==d ate( "Y") ? ' selected="selected"' : ''); $options3[]="<option value=\" {$theyear}\ " {$sel1}>{$theyear}</option>"; } $options_list3=j oin( "\r\n", $options3); echo "<select name=\"year\ " id='year' >{$options_list3}</select>"; ?>
</td>
</tr>
</table>
<input type="submit" name="sub" value="add" />
</form>
</div>
</div>
<script>
function show() {
document.getElementById("myTableData").style.display = "block";
}
function createObject() {
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
//value solve an Internet Explorer cache issue
var nocache = 0;
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('content02').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var kid_name = encodeURI(document.getElementById('kid_name').value);
var gender = encodeURI(document.getElementById('gender').value);
var month = encodeURI(document.getElementById('month').value);
var day = encodeURI(document.getElementById('day').value);
var year = encodeURI(document.getElementById('year').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', '4.php?kid_name=' + kid_name + '&gender=' + gender + '&month=' + month + '& day=' + day + '&year=' + year + '&nocache = ' + nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if (http.readyState == 4) {
var response = http.responseText;
// else if login is ok show a message: "Site added+ site URL".
document.getElementById('content02').innerHTML = 'Your contact was successfully added!' + response;
}
}
</script>
4.php
<?php
if(isset($_GET['kid_name']) && isset($_GET['gender']) && isset($_GET['year']) && isset($_GET['day']) && isset($_GET['month']) )
{
echo $newFname = $_GET["kid_name"] ;
echo $newLname = $_GET["gender"] ;
echo $newPhone = $_GET["year"] ;
echo $newEmail = $_GET["day"] ;
echo $newAddress = $_GET["month"] ;
//$insertContact_sql = "INSERT INTO `test`.`contacts` (`newFname`, `newLname`, `newPhone`, `newEmail`, `newAddress`, `group`) VALUES ('{$newFname}' , '{$newLname}' , '{$newPhone}' , '{$newEmail}' , '{$newAddress}' , '{$group}')";
//$insertContact= mysql_query($insertContact_sql) or die(mysql_error());
} else
{
echo 'Error! Please fill all fileds!';
}
?>
I am working with php language. There is a addkid button, which, when the user clicks on the button a pop type window shows the form which has NAME , GENDER AND DOB. In the form action javascript:insert(). I am using ajax for the 1st time so I am not able to understand why it's not working. I guess it should redirect me to 4.php and in 4.php it will echo the values?
I have tested your code and seems it works, I just added a div to show the results there...
You can try to add this div you are not already added it...
<div id="content02">
</div>
Here you write the response, like "Your contact was successfully added"....
I am trying to call a form and php filefrom a javascript function but it does not work. It might have to do with the cookies, it does not call the "frmSubdeptChainDailyHL" form and it does not call the "subdeptclass_reportHL.php" file, here is the code:
function submitClassChainDaily()
{
var store = readCookie('storeAccess');
var clss = readCookie('classAccess');
var subdept = readCookie('subDeptAccess');
var period = readCookie('period');
if (period == null || period == '') {
period = 'CUR';
}
document.frmClassChainDaily.period.value = period;
var storePref = readCookie('storePref');
if (storePref == null || storePref == '') {
if (store == null || store == '') {
storePref = 'ALL';
} else {
storePref = store;
}
}
if ((storePref.length) > 3 && storePref != 'ALL100') {
document.setStore.submit();
} else {
document.frmClassChainDaily.store.value = storePref;
if (clss == null || clss == '') {
clss = 'ALL';
}
document.frmClassChainDaily.clss.value = clss;
if (subdept == null || subdept == '') {
subdept = 'ALL';
}
document.frmClassChainDaily.subdept.value = subdept;
";
if ($_REQUEST['storePref']=='099')
{
echo "document.frmSubdeptChainDailyHL.submit();";
} else {
echo "document.frmSubdeptChainDaily.submit();";
}
echo "
}
}
Here is the form code:
if ($_REQUEST['storeCode'] == '099') {
echo"
<li>
<!-- SubDept Daily Sales - Chain -->
<form name=\"frmSubdeptChainDailyHL\" action=\"subdeptclass_reportHL.php\">
<input type=hidden value=\"\" name=\"store\">
<input type=hidden value=\"\" name=\"subdept\">
<input type=hidden value=\"\" name=\"clss\">
<input type=hidden value=\"\" name=\"period\">
</form>
<a style=\"display: block; text-decoration: none; color: #000\" href=\"javascript: submitSubDeptChainDaily();\">
<h3 class=\"longfield\">
<img src=\"content/images/icons/US_dollar_icon.png\" alt=\"icon\" class=\"icon\"/>
<span>Sales</span>
</h3>
</a>
</li>
You cant directly call to a php function from javascript. Make use of some ajax calls
For some reasons my javascript form validation does not go through every row in the table.
I created the table with the codes below:
The $usr variable is just a result of another process:
<form name="myForm" action="addAccessories.php" method="post" onsubmit="return validateForm(this);">
<table border="1" id="IT">
<tr>
<th>Barcode<em>*</em></th>
<th>Current stock</th>
</tr>
<?php
for($id=1; $id<=$usr; $id++){
?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $id; ?>" />
<input type="text" name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>
<td><input type="text" name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
<?php
}
?>
<tr>
<td> </td>
<td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
</tr>
</table>
</form>
The number of rows from this table is: rows = $usr + 1
My validation form codes:
<script type="text/javascript">
function validateForm(){
var errors = [];
for(i = 1; i < document.getElementById("IT").rows.length; i++){
var barcode = document.getElementById('bar_code'+i).value;
var des = document.getElementById('description'+i).value;
var num_stock = document.getElementById('num_stock'+i).value;
if(barcode == null || barcode == ""){
errors[errors.length] = "You must enter barcode.";
}
if(isNaN(num_stock)){
errors[errors.length] = "Current stock must be an integer";
}
if(num_stock < 0){
errors[errors.length] = "Current stock must be a positive number";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
This process only validates the 1st row in the table then stop. Can anyone show me what went wrong and how to fix it?
Thank you very much for your help
Your code is making life way more complex than it needs to be. A simpler approach is to just deal with the form controls, e.g. since you are already passing a reference to the form from the submit listener:
function validateForm(form) {
var errors = [];
var c, cs = form.elements;
var reB = /^bar_code/;
var reN = /^num_stock/;
var reD = /^[0-9]+$/;
for (var i=0, iLen=cs.length; i<iLen; i++) {
c = cs[i];
if (reB.test(c.name) && c.value == '') {
errors.push('You must enter barcode.'];
} else if (reN.test(c.name) && !reD.test(c.value)) {
errors.push('Stock number must be a positive integer.'];
}
}
// deal with errors...
}
Note that in the test:
> barcode == null || barcode == ""
barcode is a string, so the first test will never return true and the second is sufficient if you want to see if it's empty.
I have the following code:
Check All |
Uncheck All |
Invert Selection<br />
<table>
<tr>
<td><input type="checkbox" name="names[8]" value="yes" />Paul</td>
<td><input type="checkbox" name="names[11]" value="yes" />Bob</td>
<td><input type="checkbox" name="names[44]" value="yes" />Tom</td>
</tr>
</table>
And the following script:
function setCheckboxes3(act)
{
elts = document.getElementsByName("names[]");
var elts_cnt = (typeof(elts.length) != 'undefined') ? elts.length : 0;
if (elts_cnt)
{
for (var i = 0; i < elts_cnt; i++)
{
elts[i].checked = (act == 1 || act == 0) ? act : (elts[i].checked ? 0 : 1);
}
}
}
The script is working with other arrays without keys, but I can't get it to work with this array which has keys.
Thanks in advance
You can use getElementsByClassName:
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
var e = document.getElementsByClassName('names');
var elts_cnt = (typeof(e.length) != 'undefined') ? e.length : 0;
if (!elts_cnt) {
return;
}
for (var i = 0; i < elts_cnt; i++) {
e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
}
}
</script>
Check All |
Uncheck All |
Invert Selection<br />
<input type="checkbox" name="names[8]" class="names" value="yes" />Paul
<input type="checkbox" name="names[11]" class="names" value="yes" />Bob
<input type="checkbox" name="names[44]" class="names" value="yes" />Tom
OR you can use: getElementsByTagName
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
var e = document.getElementsByTagName('input');
var elts_cnt = (typeof(e.length) != 'undefined') ? e.length : 0;
if (!elts_cnt) {
return;
}
for (var i = 0; i < elts_cnt; i++) {
if((e[i].type) == 'checkbox') {
e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
}
}
}
</script>
Check All |
Uncheck All |
Invert Selection<br />
<input type="checkbox" name="names[8]" value="yes" />Paul
<input type="checkbox" name="names[11]" value="yes" />Bob
<input type="checkbox" name="names[44]" value="yes" />Tom
Did you get a chance to try jQuery?