Can not limit the number of check boxes to be selected - javascript

I'm using foreach loop to generate the checkboxes in my form. It is given below.
<?php $index = 0;
foreach($cameramen as $n_key){ ?>
<div class="checkbox">
<label>
<input type="checkbox" id="cameramen_<?php echo $index+1; ?>" name="cameramen" class="subscriber" value="<?php echo $index+1; ?>">
<?php
echo $n_key->emplist3;
$index++;
?>
</label>
</div>
<br/><br/>
<?php } ?>
I want to limit the number of checkboxes to be selected by the user to two.
I used the following javascript function but it not worked(It allows to select all the checkboxes).
$("input[name=cameramen]").change(function(){
var max= 2;
console.log($("input[name=cameramen]:checked").length);
if( $("input[name=cameramen]:checked").length == max ){
$("input[name=cameramen]").attr('disabled', 'true');
$("input[name=cameramen]:checked").removeAttr('disabled');
}else{
$("input[name=cameramen]").removeAttr('disabled');
}
});
Someone please help me to solve this problem which I have being struggling for hours to solve.

You can try this:
$(document).ready(function(){
$(".cb").on('click', function(e) {
var count = 0;
var list = $('.cb');
$('.cb').each(function(i) {
if($(this).is(':checked')) {
count++;
}
});
if(count > 2)
{
alert('You cannot check more than 2 checkboxes!');
$(this).prop('checked', false);
//return false;
} else {
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="cb" type="checkbox">Checkbox 1
<br />
<input class="cb" type="checkbox">Checkbox 2
<br />
<input class="cb" type="checkbox">Checkbox 3
<br />
<input class="cb" type="checkbox">Checkbox 4
</div>
Hope this helps!

Related

How to print a new value of a checkbox after having checked it?

I built a form in which I populated checkboxes with values stored in a PostGreSQL database (you can see the snippet). The checkbox are checked or not checked automatically.
Now, if I choose another value of the checkbox, I'd like to display it in an "alert" or "console.log" print.
How could I do in Javascript or Jquery ?
Thanks you very much for the help !
<div class="form-row">
<div id="man-compo" class="form-group col-md-12">
<label for="exampleInputPassword1">Composition (le texte hagiographique est composé de) :</label><br>
<?php
foreach ($checked116 as $value) {
$array12 = array("Textes historiographiques","Actes de la pratique","Textes grammaticaux","Lettres et ars dictaminis","Vers et inscriptions métriques","Lexique","Comput","Algèbre et géométrie","Autres");
$checked = "";
if(in_array($value, $array12)){
$checked = "checked";
echo '<input type="checkbox" id= "checked-man-compo-compo-1" name="checkedmancompocompo1[]" value="'.$value.'" '.$checked.' > '.$value.' <br/>';
}
}
foreach ($array12 as $i) {
$checked = "";
if(in_array($i, $checked116)){
}
else {
echo '<input type="checkbox" id= "notchecked-man-compo-compo-1" name="notcheckedmancompocompo1[]" value="'.$i.'" '.$checked.' > '.$i.' <br/>';
}
}
?>
Here is a simple example of what you're trying to do in plain JavaScript which you can mody/apply to your code.
//get all checkboxes beginning with id 'checkbox'
let checkboxes = document.querySelectorAll( "[ id^=checkbox ]" );
//add event listener to each checkbox, upon being checked/unchecked to print out value
for ( let i = 0; i < checkboxes.length; i++ ) {
checkboxes[ i ].addEventListener( "change", function() {
console.log( checkboxes[ i ].value );
});
}
<label for="checkbox1"> checkbox 1 </label>
<input type="checkbox" id="checkbox1" value=1>
<label for="checkbox2"> checkbox 2 </label>
<input type="checkbox" id="checkbox2" value=2>
<label for="checkbox3"> checkbox 3 </label>
<input type="checkbox" id="checkbox3" value=3>
<label for="checkbox4"> checkbox 4 </label>
<input type="checkbox" id="checkbox4" value=4>
I hope this is of help to you.

How to disabled table row using JS and insert the chosen option in MYSQL?

I have a PHP snippet that display the table row dynamically. Every row I there's a radio button with "Yes" and "No" option.
I created a JS function, when the user choose an option, there's a pop-box will be displayed.
If the user choose "Yes" option in the radio button and click "Ok" in the pop-box, the table row will be disabled even the radio button will be disable too. And the chosen option will be save in MYSQL.
How to save the chosen option in MySQL?
My JS snippet of disabling a row is not working. How to fix this?
PHP:
echo '<td id="resumeFile">Download Resume</td>';
echo '<td id="radioOption">
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes" name="processedOption" value="Yes" onclick="proccessedCheck()"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo" name="processedOption" value="No" onclick="proccessedCheck()"/></td>';
JS:
function proccessedCheck(){
var checked = null;
var inputs = document.getElementsByName('processedOption');
for (var i = 0; i < inputs.length; i++){
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked == null){
return false;
} else if (checked == true){
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
document.getElementById("resumeFile").title = "This option has been disabled.";
} else {
return confirm('You have chosen '+ checked.value + ', is this correct?');
}
}
Ok so if you are echo'ing the whole table from PHP just preset the parameters into the table
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script>
function proccessedCheck(id,answer) {
if (confirm('You have chosen '+ id +': '+ answer + ', is this correct?')) {
$("#processedOptionYes"+id).attr('disabled',true);
$("#processedOptionNo"+id).attr('disabled',true);
var withlink = $("#resumeFile"+id).html();
var withoutlink = $(withlink).html();
$("#resumeFile"+id).html("").append(withoutlink);
$("#input1".val(id);
$("#input2".val(answer);
$("#myform").submit();
}
}
</script>
<!-- EDIT: hidden form to submit -->
<form id="myform" method="POST" action="savedb.php">
<input type="hidden" id="input1" name="id" />
<input type="hidden" id="input2" name="answer" />
</form>
<table>
<tr>
<?php
$dir="";
$file="";
$id = 0;
//foreach($array as $row) {
$id++;
echo '<td id="resumeFile'.$id.'">Download Resume</td>';
echo '<td id="radioOption>
<label for="Yes">Yes</label>
<input type="radio" id="processedOptionYes'.$id.'" name="processedOption" value="Yes" onclick="proccessedCheck('.$id.',\'Yes\')"/>
<label for="No">No</label>
<input type="radio" id="processedOptionNo'.$id.'" name="processedOption" value="No" onclick="proccessedCheck('.$id.',\'No\')"/></td>';
//}
?>
</tr>
</table>
</body>
</html>
Contents of savedb.php, this doesn't have to be a seperate file
<?php
// Check if my post array arrived, comment this line when u done
echo "<pre>";print_r($_REQUEST);echo "</pre>"; die();
// Connect to DB
// Build SQL insert string with $_REQUEST['id'] as the primary key
?>
For starters, try replacing:
document.getElementById("resumeFile").disabled = true;
document.getElementById("radioOption").disabled = true;
with:
document.getElementById("processedOptionYes").disabled = true;
document.getElementById("processedOptionNo").disabled = true;

jquery .show() by php variable

I'm trying to trigger jquery .show() events triggered by php variables.
Here's my .php (which draws from a form submission on a separate page):
$last_pic_displayed = trim($_POST["last_pic_displayed"]);
if ( strlen($last_pic_displayed) <= 0 )
{ $last_pic_displayed = trim($_GET["last_pic_displayed"]); }
and here's my .show() code:
<script>
var lpic = "<?php echo $last_pic_displayed; ?>";
lpic = parseInt(lpic);
if (lpic == 0) {
$("#1").show();
}
</script>
I use variations on this script for multiple divs with the intention that the correct $last_pic_displayed; value will trigger the correct div to show, but so far none have.
Here's an example of the form that's posting data to my php:
<form id="buttons" action="process_form.php" method="post">
<label for="child_name"><img src="images/enter_name_text.png" alt="Enter Your Name" id="name_text"></label>
<input type="text" id="child_name" name="child_name" />
<section>
<input checked="checked" id="radio1" name="last_pic_displayed" type="radio" value="0" />
<label for="radio1"><img src="images/3_letter_text.png" alt="3 Letter Words" class="level_text">
</label>
</section>
<section>
<input checked="checked" id="radio2" name="last_pic_displayed" type="radio" value="6" />
<label for="radio1"><img src="images/4_letter_text.png" alt="4 Letter Words" class="level_text">
</label>
</section>
<section>
<input checked="checked" id="radio3" name="last_pic_displayed" type="radio" value="13" />
<label for="radio1"><img src="images/5_letter_text.png" alt="5 Letter Words" class="level_text">
</label>
</section>
<section id="submit_button">
<input type="image" name="submit" src="images/submit.png" />
</section>
</form>
Here is an example of the section of code that I'm trying to get to show when the submitted form data matches a certain value along with my script in relation:
<div class="word" id="1" data-value="1">
<img src="images/Bat.png" class="letter_text">
<form id="f1" action="results.php" method="post">
<input type="hidden" name="child_name" value="<?php $child_name; ?>" />
<input type="hidden" name="running_score" value="<?php $running_score; ?>" />
<input type="hidden" name="last_pic_displayed" value="1" />
<input type="hidden" name="correct_spelling" value="BAT" />
<input type="hidden" name="last_pic_flag" value="NO" />
<input type="hidden" name="level" value="3_letter" />
<input type="text" name="submitted_spelling" />
<input type="image" class="submit" src="images/submit.png" />
</form>
</div>
<script>
var lpic = "<?php echo $last_pic_displayed; ?>";
lpic = parseInt(lpic);
if (lpic == 0) {
$("#1").show();
}
alert(lpic);
</script>
I'm pretty new at all this, so I definitely appreciate your help.
EDIT: Updated with syntax corrections; problem currently persists.
EDIT2: Updated with form example.
EDIT3: Updated with parseInt() and example of the div I'm trying to show.
You need to parseInt() the "lpic" variable Like that way :
var lpic = "<?php echo $last_pic_displayed; ?>";
lpic = parseInt(lpic);
if (lpic == 0) {
$("#1").show();
}
use it:-
var lpic = "<?php echo $last_pic_displayed; ?>";
lpic = parseInt(lpic);
if (lpic == 0) {
$("#1").show();
}
use this
<script>
var lpic = "<?php echo $last_pic_displayed; ?>"; // this must in ""
if (lpic == '0') { // must be == instead =
$("#1").show();
}
</script>

jQuery validation to select at least one checkbox

I have written following code to select multiple checkbox and also need to validate at least one checkbox is selected. In the following code data submission to database is working if I remove onsubmit="return validate_form()". But I want to validate at least one checkbox is selected.
Following is the code:
<?php
$link=mysql_connect("localhost","root","") or die("cant connect");
mysql_select_db("country_ajax",$link) or die("cant select db");
extract($_POST);
$check_exist_qry="select * from language";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_language=explode(',',$my_value['language_name']);
}
if(isset($submit))
{
$fname=$_POST['fname'];
$sname=$_POST['sname'];
$all_language_value = implode(",",$_POST['language']);
if($total_found >0)
{
//update
$upd_qry="UPDATE language SET language_name='".$all_language_value."' where member_id = 75";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO language(language_name) VALUES('".$all_language_value."') where member_id = 75";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="" onsubmit="return validate_form()";>
<input type="text" name="fname"/><br>
<input type="text" name="sname"/><br>
languahe you know <br/>
<input type="checkbox" name="language[]" value="1" <?php if(in_array(1,$my_stored_language)){echo "checked";}?>><label>PHP</label><br>
<input type="checkbox" name="language[]" value="2" <?php if(in_array(2,$my_stored_language)){echo "checked";}?>><label>Java</label><br>
<input type="checkbox" name="language[]" value="3" <?php if(in_array(3,$my_stored_language)){echo "checked";}?>><label>c</label><br>
<input type="checkbox" name="language[]" value="4" <?php if(in_array(4,$my_stored_language)){echo "checked";}?>><label>javascript</label><br>
<input type="checkbox" name="language[]" value="5" <?php if(in_array(5,$my_stored_language)){echo "checked";}?>><label>c#</label><br>
<input type="checkbox" name="language[]" value="6" <?php if(in_array(6,$my_stored_language)){echo "checked";}?>><label>.net</label><br>
<input type="submit" name="submit" value="submit">
</form>
<script>
function validate_form()
{
valid = true;
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
return valid;
}
</script>
function validate_form()
{
valid = true;
$('form').find('input[type=checkbox]').each(function(){
if($('input[type=checkbox]:checked').length == 0)
{
alert ( "ERROR! Please select at least one checkbox" );
valid = false;
}
)};
return valid;
}
Try this one.

How to show an alert if all checkboxes aren't checked?

I want alert if check-box is not checked (- this is working )
and
Alert if ALL check-box is not checked ( need help in this )
CheckBox :
<input type="checkbox" value="1" id="data" name="data[]">
<input type="checkbox" value="2" id="data" name="data[]">
<input type="checkbox" value="3" id="data" name="data[]">
Button :
<input name=\"submitclose\" type=\"submit\" value=\"Close\" id=\"submitclose\">
Below is my Jquery :
echo "<script>
jQuery(function($) {
$(\"input[id='submitclose']\").click(function() {
var count_checked = $(\"[id='data']:checked\").length;
if (count_checked == 0) {
alert(\"Please select a Packet(s) to Close.\");
return false;
} else{
return confirm(\"Are you sure you want to Close these Packet?\");
}
});
});
</script>";
Try,
HTML:
<input type="checkbox" value="1" id="data1" name="data[]">
<input type="checkbox" value="2" id="data2" name="data[]">
<input type="checkbox" value="3" id="data3" name="data[]">
JS:
var allCheckBox = $("[id^='data']")
var count_checked = allCheckBox.filter(":checked").length;
if (count_checked == 0) {
alert("All check boxes are not checked");
} else if(count_checked != allCheckBox.length) {
alert("some of the check boxs are not checked");
} else{
return confirm("Are you sure you want to Close these Packet?");
}
$(\"input[id='submitclose']\").click(function(){
var count = 0;
$('input#data').each(function(){
if ($(this).attr('checked') == true){
count++ //if a checkbox is checked the variable count will be greater then 0.
}
})
if (count == 0){ //nothing is checked.
alert("Please check at least one of the checkboxes");
}else{ //something is checked.
//code to execute.
}
})

Categories