I have checkboxes whose value attribute is coming from database.I want the user to always check the checkboxes having same value if he does not then alert using javascript.I tried to do this using the following javascript code but no use
<script>
function ck()
{
var x,item,f;
list=document.getElementById("yo");
f=list[0].value;
for(index=1;index<list.length;++index)
{
item=list[index];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>
Below is the PHP code for checkbboxes
<?php
$flag1=-1;
$conn = mysqli_connect("localhost", "root","","discvr");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
$time_id=$j;
$sql="select status from final where location = '$location' AND date='".$cur_date."' AND time_id=$time_id";
$query=mysqli_query($conn,$sql);
if(!$query)
{
$status=0;
echo "Hi";
}
else
{
if($row=mysqli_fetch_array($query))
{
//echo "hi";
$status=$row['status'];
}
else
$status=0;
//echo $time_id;
}
if($i==0)
echo "<td><input type='checkbox' id='yo' name=time[] value=".$j." value='".$status."' onclick='ck()' > $status </td>";
else
echo "<td><input type='checkbox' id='yo' name=time".$i."[] value=".$j." value='".$status."' onclick='ck()' >$status</td>";
}
echo "</tr>";
}
?>
give unique id's to each checkbox even you are not using them.
Note: on your page id's should be unique.
try like this:
use your connection and other this ,it is for demo.
<?php
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
if($i==0)
echo "<td><input type='checkbox' id='yo$i' name=time[] value=".$j." value='".$status."' onclick='ck(this.value)' > $status </td>";
else
echo "<td><input type='checkbox' id='yo$i' name=time".$i."[] value=".$j." value='".$status."' onclick='ck(this.value)' >$status</td>";
}
echo "</tr>";
}
?>
javascript:
<script>
function ck(value)
{
var x,item,f;
list= document.getElementsByTagName("input");
f=value;
console.log(f);
for(i=1;i<list.length;++i)//change your logic here don't know what you are trying here
{
item=list[i];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>
Related
Here i am retriving data from database and i am doing insert,update and delete of data using checkbox.My problem is when i click more than two checkbox than also i am moving to update.php page but what i actually want is that when i click on update button first it will check that only one checkbox is selected from list if not than alert message should display like select only one checkbox. please help.Thanks in advance
Here i have put my code.
<!DOCTYPE html>
<html>
<head>
<title>Insert Update Delete</title>
</head>
<body>
<form name="dataform" id="data" action="" method="get">
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db_new", $connection);
$query=mysql_query("select * from student_info");
echo "<table>";
while($row=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>"; ?> <input type="checkbox" id="box" name="num[]" class="other" value="<?php echo $row["id"];?>" /> <?php echo "</td>";
echo "<td>"; echo $row["roll_no"]; echo "</td>";
echo "<td>"; echo $row["name"]; echo "</td>";
echo "<td>"; echo $row["division"]; echo "</td>";
echo "<td>"; echo $row["std"]; echo "</td>";
echo "<td>"; echo $row["gender"]; echo "</td>";
echo "<td>"; echo $row["subject"]; echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="insert" value="insert"/>
<input type="submit" name="update" value="update"/>
<input type="submit" name="delete" value="delete"/>
</div>
</form>
<?php
if(isset($_GET["insert"]))
{
$box = $_GET['num'];
$count =count($box);
if ($count == 0){
header('Location:insert.php');
}
elseif($count == 1){
header('Location:data.php');
}
}
?>
<?php
if (isset($_GET['update'])){
$box = $_GET['box'];
$count =count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:update.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
echo $id;
header("location:update.php?id=".$id);
}
}
}
?>
<?php
if (isset($_GET['delete'])) {
$box = $_GET['num'];
$count = count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:data.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
mysql_query("delete from student_info where id = $id");
}
}
}
?>
</body>
</html>
You could use a radio button for this instead of a checkbox.
see sample here
Use Radio Instead of CheckBox
Or if you must use a checkbox do this:
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
I would use a radio button, however I don't know your situation so here's a solution using jQuery. You want to select all of the checkboxes that are checked then see if the length of that array is greater than one. Here's the javascript code you'll need and a jsbin if you want to look at it.
http://jsbin.com/qakuzajaza/edit?js,output
$("#submitbutton").click(function() {
var count = $("input[type=checkbox]:checked").length;
if (count > 1) {
alert("Only 1 can be selected");
} else {
// submit data
}
});
1. Try this, it will not allow you to check only one checkbox at a time.
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('#ckeckboxlistId').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
The approaches are more or less similar. Try this:
submitForm(); //according to an event you prefer (click some button or anchor , no button over $ .ajaks.
function submitForm(){
var tag = document.getElementById("tdForm");
var chkbx = $(tag).find("input[type='checkbox']:checked").length;
if (chkbx !== 0) {
if (chkbx > 1) {
alert("more then 1");
}else{
alert("form submited"); //$(tag).submit();
}
}else{
if (chkbx === 0) {
alert("nothing cecked");
}
}
};
Tested works for me. Hope it helps!
While I think the radio buttons or previous validation, and interception of errors on the rules for completing the form, are much more affordable.
I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.
I am trying to get a table of names checked,
and send this array to a PHP page.
But I dont know how, I began by this code:
$(".ok").click(function(){
$("input[type='checkbox']:checked").each(function() {
var tt = $(this).val();
alert(tt);
});
});
echo "<table>";
foreach ($result as $data) {
echo "<tr>";
echo "<td><input type='checkbox' value='$data[0]' /></td><td>$data[0]</td>";
echo "</tr>";
}
echo "</table>";
Try..
$(".ok").click(function(){
//check if any are checked and if so redirect..
if($("input[type='checkbox']:checked").length > 0)
window.location.href = 'page.php?'+$("input[type='checkbox']:checked").serialize();
});
then in page.php..
$result = $_GET;
if(count($result)){
foreach($result as $data){
echo "<tr>";
echo "<td><input type='checkbox' value='$data' /></td><td>$data</td>";
echo "</tr>";
}
}
please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED
You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?
if (isset($_POST['dept']) && isset($_POST['batch']) && isset($_POST['Month']) && isset($_POST['Year']) && isset($_POST['semester'])) // based on these values selected from database
{
$dept = $_POST['dept'];
$batch = $_POST['batch'];
$month = $_POST['Month'];
$year = $_POST['Year'];
$semester = $_POST['semester'];
$query = db_select('student_master');
$query->fields('student_master', array('reg_no','name','dob','dept_code','degree','batch_year'));
$query->condition('dept_code',$dept,'=') AND $query->condition('batch_year',$batch,'=');
$results = $query->execute();
echo "<table>";
echo "<tr>";
echo "<td><label for='reg_no'> Registration Number </label></td>";
echo "<td>";
echo "<select name='reg_no'>";
foreach($results as $student_result)
{
echo "<option value ='$student_result->reg_no'> $student_result->reg_no</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
$query = db_select('subject');
$query->fields('subject', array('subject_name','credits','subject_code'));
$query->condition('dept_code',$dept,'=') AND $query->condition('semester_appear',$semester,'=') ;
$subject_results = $query->execute();
echo "<tr>";
echo "<td><label for='Subject'>Subject Name</label></td>";
echo "<td>";
echo "<select name = 'sub_name' id = 'sub_name'>";
foreach($subject_results as $subjects_result)
{
echo "<option value ='$subjects_result->subject_code'> $subjects_result->subject_name</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td><label for='Subject'>Subject Serial Number</label></td>";
echo "<td>";
echo "<select name='subject_serial' id = 'sub_name'>";
if ($semester == "SEMESTER-I")
{
for($i=101; $i<=110; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-II")
{
for($i=201; $i<=210; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-III")
{
for($i=301; $i<=310; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
elseif ($semester == "SEMESTER-IV")
{
for($i=401; $i<=410; $i++ )
{
echo "<option value ='$i'>$i</option>";
}
}
echo "</select>" ;
echo "</td>";
echo "</tr>";
echo "</table>";
}
else
{
return "please check the your input";
}
How to add select box field dynamically after clicking add button (the selected box contain the datas from database after clicking the add button, and same selected value store in database) by using php or javascript and store selected value in selected box to database
Create a PHP page that returns the required HTML string only
And then on client side using jquery you can append that html to desired element
e.g.
$("#btnAddnew").click(function(){
$.get('ajax/test.php?id=1', function(data) {
$('#divDropdown').html(data);
});
});
Then in post you can pass the selected dropdown's value using javascript
e.g. If it is like
then $("#drpRegNum").val() would give you the selected value