I want to check all the check-boxes within a html div if the "parent checkbox" for that div is checked. I'm new at JavaScript/PHP/HTML. Can anyone provide an useful explanatory example?
Here's my code:
<form>
<?php
while(list($k, $v)=each($Aff))
{
if ($k == 0)
{
array_push($parentAff, substr($v, 0, 2));
$substring = $v;
echo ('<div id ="Div'.$v.'">');
}
if ((substr($substring, 0, 2) != substr($v, 0, 2)) && (strlen($substring) != 1))
{
echo ('</div>');
echo ('<div id ="'.$v.'">');
array_push($parentAff, substr($v, 0, 2));
$counter++;
$substring = $v;
echo "<hr>";
}
echo ('<input type="checkbox" name="Aff[]" id="'.$v.'" value="'.$v.'" /><label for="text'.$k.'">'.$v.'</label>');
$substring = $v;
}
echo ('</div>');
?>
</form>
The number of checkboxes within a div depend on what data comes out of the database to the array Aff[]. The parent checkbox for each div would be the one in the parentAff array which is identified by the div id.
See the following code pen for an example of how to accomplish this using JS.
https://codepen.io/psmith104/pen/gByKzx
I've also included the code here as well.
Here is the HTML
<div>
<input type="checkbox" class="parent" /> Parent Checkbox
<br/>
<input type="checkbox" /> Child 1
<br/>
<input type="checkbox" /> Child 2
<br/>
<input type="checkbox" /> Child 3
<br/>
<input type="checkbox" /> Child 4
</div>
And here is the JS
document.querySelectorAll("input[type=checkbox].parent").forEach(function(parent) {
parent.addEventListener("click", function(e) {
e.target.parentElement.querySelectorAll("input[type=checkbox]:not(.parent)").forEach(function(child) {
child.checked = true;
});
});
});
Related
I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits.
Conditions:
Only if False Hit radio button is selected
The remarks text field cannot be empty (Compulsory)
Currently, I have used JavaScript to check if the text field (Remarks) is empty.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Please enter remarks for false hits selected.");
return false;
};
I am also able to check which radio button is selected with JavaScript.
<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />
if(document.getElementById('falsehit').checked) {
//False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
//True Hit radio button is checked
}
However, I am quite stuck at linking both conditions together. Is there a simpler method to this? Any help is greatly appreciated. Thank you in advance.
This is how my Form looks like.
<body bgcolor="#FFFFFF">
<br />
<div align="center" class="h1">
<h1>Entity Search</h1><br />
</div>
</html>
<br />
<?php
include("db_connect.php"); //connect to database
#$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture
the user's LanID as the UserID
if($loginid == "")
{
$userID = $_SESSION['loginid'];
}
else
{
$_SESSION['loginid'] = $loginid;
$userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];
//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');
$userID = $_SESSION['loginid'];
$loginid = "";
$entityfromform = $_GET["entity"];
?>
<br />
<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);
//to retrieve the department name from the user database and insert
department name of the user into the records
$namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE
LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);
while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
$nameontop = iconv("gb2312","UTF-8",$row['Name']);
$admincheck = iconv("gb2312","UTF-8",$row["Role"]);
$deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}
$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />";
//variable to insert into the table as result
//search for keyword from form in the Entity Table List where Name =
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);
//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{
$name[$i] = $row["Name"];
$brn[$i] = $row["Business_Registration_Number"];
$address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}
if(#$name != NULL) //Positive Result
{
echo "<input type='button' name=uncheck' value='Uncheck All'
class='uncheck' onClick='window.location.reload()'>"; //uncheck all
function where it clears all changes
echo "<h2><div align='center'>Results found for:
$entityfromform</div></h2><br />";
//table to display the data
echo "<div align='center'>
<table>
<tr>
<th>Name</th>
<th>Business Registration Number</th>
<th>Registered Address</th>
<th>Applicable Limb of Related Party Group</th>
<th>True Hit</th>
<th>False Hit</th>
<th>Unable To Ascertain</th>
<th>Remarks, for false hit</th>
</tr>
</div>";
echo "<strong><div class='wording'>Positive Hit: </div></strong>";
echo "<br /><br />";
$x=0;
?>
<!--The form data is sent for processing to action_handler.php by HTTP POST method-->
<form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
<?php
//data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
for($x=0;$x<$i;$x++)
{
echo "<tr>
<td>" . $name[$x] . "</td>
<td>". $brn[$x] . "</td>
<td>". $address[$x] . "</td>
<td>". $group[$x] . "</td>
<td>
<label class='container'>
<input type='radio' id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label><input type='text' name='".$text[$x]."'>
</label>
</td>
</tr>" ;
}
echo "</table>"; //table closed
echo "<br /><br /><br />";
echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
?>
</form>
<?php
//sessions to be used in others
$_SESSION['num'] = $x;
$_SESSION['entityfromform'] = $entityfromform;
}
else
{
echo "<div align='center'><h2>Results found for: $entityfromform</h2>
<br />";
echo "<div class='wording' align='center'>$negative</div><br><br>
<br>";
}
?>
</table>
</body>
your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; you can create a function for your requirement like:
function doSubmit()
{
if(document.getElementById('falsehit').checked)
{
if(document.getElementById("roll-input").value == '')
{
alert("Please enter remarks for false hits selected.");
return false;
}
}
return true;
}
and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false.
Hope this helps; let me know if I'm missing to understand your problem here..
Happy coding...
You can use a set of if statements like below. This basically checks if the falsehit radio button is checked. If it is, then it checks if the text is empty. If the text is empty, it alerts what you wanted it to. If the text isn't empty, it submit's the form.
Also, if falsehit is not checked, it automatically submit's the form.
As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. If they aren't, you get an alert message saying Please select all accordingly. Otherwise, it just works the same as before.
function empty() {
var text;
var groups = document.querySelectorAll("[id^=group]");
var selected = {};
var radioButtons;
var submitForm = true;
groups.forEach(e1 => {
radioButtons = e1.querySelectorAll("input[type=radio]");
radioButtons.forEach(e2 => {
if (e2.checked) {
selected[e1.id] = true;
}
});
if (selected[e1.id] == undefined) {
selected[e1.id] = false;
}
});
groups.forEach(e => {
text = e.children[0].value;
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].id == "falsehit") {
if (e.children[i].checked) {
if (text.length == 0) {
alert("Please enter remarks for false hits selected.");
submitForm = false;
}
} else if (selected[e.id]) {
//Don't need to do anything. Just need to prevent the next else from accessing these values
} else {
alert("Please select all accordingly.");
submitForm = false;
}
}
}
});
if (submitForm) {
document.getElementById("form").submit();
}
}
<form id="form">
<fieldset id="group1">
<input type="text" id="roll-input" />
<input type="radio" name="group1" id="truehit" value="true" />
<input type="radio" name="group1" id="falsehit" value="false" />
</fieldset>
<fieldset id="group2">
<input type="text" id="roll-input" />
<input type="radio" name="group2" id="truehit" value="true" />
<input type="radio" name="group2" id="falsehit" value="false" />
</fieldset>
<input type="button" value="Submit" onclick="empty()" />
</form>
function check_uncheck(truefalse) {
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form.chkboxarray[i].checked = true;
} else {
form.chkboxarray[i].checked = false;
}
}
}
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
The snippet shows how it works without connection to a database
I am trying to save the data that is sent from the checklist to a database but i'm stuck. I was thinking of using a foreach but I don't know what to put in it.
I though of putting it as:
foreach($_POST['id'] as $add){
insert into database...
}
How do I do this?
If I do this as Fred-ii and xjstratedgebx suggested where I just change name="chkboxarray" to name="chkboxarray[]" then the javascript code would stop working.
<?php
include '../conec.php';
mysql_select_db("test",$conec)or die('Database does not exist.') or die(mysql_error());
$sql = mysql_query("SELECT * FROM user WHERE state='Not Signed Up'");
?>
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<?php
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$name = $row['name'];
$lName= $row['lName'];
$concate = $name.' '.$lName;
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
}
?>
<!--<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />-->
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
<script type="application/javascript">
function check_uncheck(truefalse){
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for(var i=0;i < boxes;i++){
if (truefalse) {
form.chkboxarray[i].checked=true;
} else {
form.chkboxarray[i].checked=false;
}
}
}
</script>
If you change the name of your checkbox from "chkboxarray" to "chkboxarray[]", then any boxes that are checked when the form is submitted will pass their values as an array to the server under the key of "chkboxarray".
Basically, change this line:
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
To:
echo '<input type="checkbox" name="chkboxarray[]" value="'.$id.'" />'.$concate.'<br />';
As a result, if you var_dump the $_POST super global, you should see something like:
array(1) {
[chkboxarray]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
In the example above, the checkboxes for id's 3 and 4 were checked, so they were sent to the server.
Once you have that array, inserting it into your database depends heavily on what you're trying to accomplish and your database's schema.
Hope that helps.
Also, in fairness, this is exactly what #Fred meant in his comment.
Edit 1
To make the javascript work with the change of the input name, you'll need to update all the places in your javascript where you were referencing the name of the input to the new name (chkboxarray[]).
The resulting code should look like this:
<script type="application/javascript">
function check_uncheck(truefalse) {
var boxes = document.forms[0]["chkboxarray[]"].length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form["chkboxarray[]"][i].checked = true;
} else {
form["chkboxarray[]"][i].checked = false;
}
}
}
</script>
I've created a fiddle to show this works for checking/unchecking all the boxes: https://jsfiddle.net/solvomedia/3Ln468u3/
This question is a follow up to what I previously asked (HTML Form Number Type Unique User Input) but now I'm making the form more dynamic.
The following form asks users to list there 3 favorite genres of music:
<form id="genre" name="genre" method="post" action="musicsell.php">
<input type="checkbox" name="genre[]" id="Rap" value="Rap"/>Rap<br />
<input type="checkbox" name="genre[]" id="HipHop" value="HipHop"/>HipHop<br />
<input type="checkbox" name="genre[]" id="RnB" value="RnB"/>RnB<br />
<input type="checkbox" name="genre[]" id="Rock" value="Rock"/>Rock<br />
<input type="checkbox" name="genre[]" id="Jazz"value="Jazz"/>Jazz<br />
<p>
<input type="submit" value="Next">
<br />
</p>
</form>
From there, I am using the following code to make sure that they only use numbers 1,2, and 3 and a foreach loop to list what they have checked but how can I make sure they do not use the same number twice?
<body>
The genre(s) you selected are: <br />
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];
if(isset($_POST['genre'])) {
foreach ($name as $genre) {
?>
<input type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" max="3" min="1" />
<?php echo $genre ?>
<br />
<?php
}
}
?>
<input type="submit" name="button" id="button" value="Submit" />
</form>
</body>
This was the old javascript code from the previous question but now the id="" is generated by PHP above:
<script type="text/javascript">
function item() {
cake = Number(document.getElementById('cake').value);
twizlers = Number(document.getElementById('twizlers').value);
taffy = Number(document.getElementById('taffy').value);
if (cake == twizlers) {
alert("Some alert cake or twizlers");
return false;
} else if (twizlers == taffy) {
alert("Some alert taffy or twizlers");
return false;
} else if (taffy == cake) {
alert("Some alert taffy or cake");
return false;
} else {
return true;
}
}
</script>
How can this be done now? Does it have to be in a foreach loop? Any suggestions will be appreciated.
Unless they hack the form or build their own POST submission, they can't "use" the same checkbox twice. But you can easily check for duplicate values:
$counts = array_count_values(array_values($_POST['genre']));
foreach($counts as $form_value => $cnt) {
if ($cnt > 1) {
echo "$form_value was entered more than once";
}
}
I created a code which displays an information by clicking on a RADIO and other information by clicking on another RADIO.
Works normally, but when I update the page, even CHECKED, shows no information. Then I have to click again on the RADIO that is already CHECKED information to appear.
Anyone know how to solve?
Follow the code below:
<script>
// COLOR BG OR IMG BG
$(document).ready(function(){
$("input[name$='userBgOrImg']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#"+test).show();
});
});
</script>
<style type="text/css">
.desc { display: none; }
</style>
<div><label><input type="radio" name="userBgOrImg" value="1" <?php $id = $res_select["id"]; if ( $userBgOrImg == 1 ) { echo "checked=\"checked\"";} else { echo "";}?>>Cor de Fundo</label></div>
<div><label><input type="radio" name="userBgOrImg" value="2" <?php $id = $res_select["id"]; if ( $userBgOrImg == 2 ) { echo "checked=\"checked\"";} else { echo "";}?>>Imagem de Fundo</label></div>
<div> <br /> <br /> </div>
<div id="1" class="desc">
<label for="userBgBody">Cor do fundo do Site</label>
<input type="text" class="form-control bscp span12" value="<?php $id = $res_select["id"]; echo $userBgBody; ?>" id="userBgBody" name="userBgBody">
<hr />
</div>
<div id="2" class="desc">
<label for="userImgBody">Imagem de fundo do site</label>
<input type="text" class="span12" name="userImgBody" id="userImgBody" placeholder="Imagem do fundo do site" value="<?php $id = $res_select["id"]; echo $userImgBody; ?>" />
<hr />
<label for="userImgBodyRepeat">Repetir imagem de fundo</label>
<span> <input type="radio" name="userImgBodyRepeat" value="repeat"> Sim</span> <span> <input type="radio" name="userImgBodyRepeat" value="no-repeat" selected="selected"> Não
<hr />
</div>
Thank you in advance for your help.
Try this,
$(document).ready(function(){
var did=$("input[name$='userBgOrImg']:checked").val();
if(did)
{
$("#"+did).show();
}
// your remaining code
});// document.ready function close
Demo
You need to try
$(document).ready(function(){
$("input[name$='userBgOrImg']").change(function() {
var test = $(this).val();
$("div.desc").hide();
if(this.checked) {
$("#"+test).show();
}
}).filter(':checked').change();
});
Tr this..
$(document).ready(function () {
$("input[name$='userBgOrImg']").click(function () {
var value = $(this).val();
if(value)
{
$("#"+value).show();
}
});
I want to hide my div when a radio button is clicked, but cannot figure it out for the life of me.. Here is my code:
<li>
Residential
<input type="radio" name="fee" id="residential" class="app_fee"
value="<?php echo "$applicationFee_residential" ?>"
onChange="mech_application.fee1.value = eval(mech_application.residential.value)"
<?php if (isset($_POST['fee'])) {
print($residentialYes ? "CHECKED" : "");
} ?> />
</li>
<li>
Apartment/Commercial
<input type="radio" name="fee" id="apartment" class="app_fee"
value="<?php echo "$applicationFee_Apartment" ?>"
onChange="mech_application.fee1.value = eval(mech_application.apartment.value)"
<?php if (isset($_POST['fee'])) {
print($apartmentNo ? "CHECKED" : "");
} ?> />
</li>
<li>
Revision
<input type="radio" name="fee" id="revision" class="app_fee"
value="<?php echo "$revision" ?>"
onChange="mech_application.fee1.value = eval(mech_application.revision.value)"
<?php if (isset($_POST['revision'])) {
print($revisionYes ? "CHECKED" : "");
} ?> />
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST['fee'])) {
$problem = TRUE;
print '<p class="error">Please select the application type</p>';
$error = TRUE;
}
}?>
</li>
And I want to hide this div when either Residential or Apartment or clicked, and show it when revision is clicked:
<div class="revision_hidden">
Application ID:
<input type="text" name="revision_application_id" size="12" maxlength="40"
value="<?php if (isset($_POST['revision_application_id'])) {
print htmlspecialchars($_POST['revision_application_id']);
} ?>"
placeholder="Application ID"/>
</div>
Any and all help is appreciated! Thank you!
Give your div an id:
<div class="revision_hidden" id="my_div"> ...
Add an onclick function to your radiobuttons:
<input type="radio" name="fee" id="residential" onclick="my_function(this)" ...
<input type="radio" name="fee" id="apartment" onclick="my_function(this)" ...
<input type="radio" name="fee" id="revision" onclick="my_function(this)" ...
And add a JavaScript function:
function my_function(elm)
{
if(elm == document.getElementById('residential') || elm == document.getElementById('apartment'))
{
//document.getElementById('my_div').style.visibility = "hidden";
document.getElementById('my_div').style.display = "none";
}
else if(elm == document.getElementById('revision'))
{
//document.getElementById('my_div').style.visibility = "visible";
document.getElementById('my_div').style.display = "block";
}
}
You can use jQuery to hide elements real easy.
$('#id_of_div').hide()
For doing something on the radio button being clicked, use more jQuery
$('#id_of_radioBtn').clicked(function(){
//do something
});