Check and Count number of checked checkboxes - javascript

I am creating checkboxes(Array of checkbox) as per number of users.
If there is no user than checkbox will not created.
Problem :
I want to check that if checkbox(es) is/are exist or not and
if checkbox(es) exist than i want to count checkboxes that are checked.
Code:
<?php
if (isset($companyusers) && $companyusers != array()) {
foreach ($companyusers as $key => $value) {
?>
<div class="div_to_hide">
<label class="checkbox" style="display: inline-block !important">
<input name="noti[<?php echo $value->id; ?>]" id="" type="checkbox" class="checkbox_input" value="<?= $value->first_name ?>">
<span class="search_text">
<?= $value->first_name ?>
</span>
</label>
</div>
<?php
}
}
?>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn smbtn btn-success">
<?php echo Yii::t('app', 'Send'); ?>
</button>
</div>
</div>

Try:
Demo: https://jsfiddle.net/r00xxgk5/
if($('input:checkbox[name="noti[]"]').length > 0) { // check length of checkbox if > 0
var sList = "";
$('input:checkbox[name="noti[]"]').each(function () { // loop throgh all checkbox and detect if checked or not
sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
});
console.log (sList);
}

how about using count:
count($noti);

Related

show and hide element in jquery with ajax

I create survey poll in wordpress plugin to display questions i use ajax to display it
this is my html code
<div id="my_poll">
<button class="start" id="start"><b><?php _e('Start poll questions'); ?></b></button>
<div id="poll" class="container mt-sm-5 my-1">
<form>
<?php
if ($ques->have_posts()) {
while ($ques->have_posts()) {
$ques->the_post();
global $post;
$ID = $post->ID;
$option = get_post_meta($ID, "op1", true);
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id=' . $ID . '&nonce=' . $nonce);
$ques_id = 'Q-' . $ID;
?>
<div id="<?php echo $ques_id ?>" class="questions">
<div class="question ml-sm-5 pl-sm-5 pt-2">
<h3><b><?php _e('Poll Survey'); ?></b></h3>
<div class="py-2 h5"><b class="msg"><?php the_title() ?></b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options">
<label class="options"><?php _e($option['op1']['op1']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op1']['op1']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op2']['op2']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op2']['op2']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op3']['op3']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op3']['op3']) ?>"> <span class="checkmark"></span> </label>
</div>
<div class="d-flex align-items-center pt-3">
<div class="ml-auto mr-sm-5">
<button class="btn btn-success">
<?php
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $ID . '" href="' . $link . '">submit</a>';
?>
</button>
</div>
</div>
</div>
</div>
<?php
}
}
?>
</form>
</div>
</div>
and this is my ajax to show and hide elements
jQuery(document).ready(function() {
jQuery("#poll").hide();
var count = 0;
jQuery(".start").click(function(e) {
jQuery("#poll").show();
jQuery(".start").hide();
});
jQuery(".user_vote").click(function(e) {
e.preventDefault();
option = jQuery('input[name="framework"]:checked').val();
post_id = jQuery(this).attr("data-post_id");
nonce = jQuery(this).attr("data-nonce");
var idArr = [];
jQuery(".questions").each(function() {
idArr.push(jQuery(this).attr("id"));
});
jQuery.ajax({
type: "post",
dataType: "json",
url: myAjax.ajaxurl,
data: {
action: "my_user_vote",
post_id: post_id,
nonce: nonce,
option: option,
},
success: function(response) {
if (response.type == "success") {
count++;
if (count < idArr.length) {
jQuery(".questions").hide();
jQuery("#" + idArr[count]).show();
} else {
jQuery("#my_poll").hide();
alert('Thank you for your time.')
}
} else {
alert("Your vote could not be added");
}
},
});
});
});
in this jquery ajax whene i click start button i display all questoins divs.
but i want display the first question div.
Does anyone have any solutions?
Change the on click event function like below;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery("#poll:first").show(); // id selector!
});
Better way, wirte "poll" word into the class attribute, dont use same id more than one time. If you change the id and class of the elements, your code must be like this;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery(".poll:first").show(); // class selector
});
Also, you can use $ character instead of Jquery;
jQuery("div") EQUAL $("div")
Another way to find first element;
$(".start").click(function(e) {
$(".start").hide();
$(".poll").eq(0).show(); // class selector
});

How to pick up values from multiple radio buttons and print in dynamic form?

I cannot echo radio button values to a dynamic tables which is constructed from php.
I have succeed to have Jquery auto update "name" for the radio buttons for every added row. However, the radio value seems only pick up the value from the first row.
<?php
//Pick up the index Row for constructing the tables
if(isset($_POST['submit'])) {
$row = explode("_", $_POST['rowNumber']);
if($row[1] > 0){
$maxRow = $row[1];}
};
//Pick up form input
$vitalTime = $_POST['vitalTime'];
$vitalResRate = $_POST['vitalResRate'];
echo "<table>";
echo "<tr>";
for ($i = 0; $i < $maxRow; $i++) {
//Pick up radio form input
$radCons = $_POST['radCons' . $i];
var_dump($radCons);
echo $i;
echo "</tr><tr>";
echo "<td>Vital time:" . $vitalTime[$i] . "</td>";
echo "<td>Respiration: " . $vitalResRate[$i] . "</td>";
echo "<td>Level of Conscousness ". $radCons ."</td>";
}
echo "</tr>";
echo "</table>";
?>
<form method="POST">
<div class="row cloned-row">
<div class="col-sm">
<h3>Time</h3>
<input name="vitalTime[]" id="vitalTime_1" type="text">
</div>
<div class="vitalCons col-sm">
<h3>Level of Conscousness</h3>
<div class="form-check">
<input name="radCons0" class="form-check-input" type="radio" value="Alert">
<label class="form-check-label">Alert</label>
</div>
<div class="form-check">
<input name="radCons0" class="form-check-input" type="radio" value="Voice">
<label class="form-check-label">Voice</label>
</div>
<div class="form-check">
<input name="radCons0" class="form-check-input" type="radio" value="Pain">
<label class="form-check-label">Pain</label>
</div>
</div>
</div>
<div class="row">
<input class="btn" name="submit" type="submit" value="Submit"></input>
</div>
<div class="row">
<input name="rowNumber" id="rowNumber" type="text" value="Row_1">
</div>
</form>
var btnAdd = $('#btnAdd');
btnAdd.click(function(){
//Select last ID
var vitalTime = $('.cloned-row .col-sm input[type=text]:nth-child(2)').last().attr('id');
var vitalCons = $('.cloned-row .vitalCons input[type=radio]').last().attr('name');
var split_id = vitalTime.split('_');
var splitResRate = vitalResRate.split('_');
//New Index
var index = Number(split_id[1]) + 1;
//Testing Variable
console.log(vitalCons);
console.log(vitalResRate);
console.log(index);
$(rowNumber).val("Row_" + index);
//Create Clone
var newRow = $(".cloned-row:last").clone(true);
console.log(newRow);
//Set id or name of new elements on cloned Row
$(newRow).find('.col-sm input[type=text]:nth-child(2)').attr("id","vitalTime_"+index);
$(newRow).find('.vitalCons input[type=radio]').attr("name","radCons" + index);
//Set Value
$(newRow).find('.col-sm input[type=text]:nth-child(2)').val("vitalTime_"+ index);
//Insert Element
$(newRow).insertAfter(".cloned-row:last");
});
//Drop Vital Sign Table
var btnDrop = $('#btnDrop');
btnDrop.click(function(){
$(".cloned-row:last").remove();
});
I expect for every new row, the radio buttons should loop and ouput accordingly to the "index" variable. For example, radConsc1, radConsc2 and so on (generated by java-script when click "add" button in html) should be output but the radio button array can only hold the first value of radCons0 (testing from var_dump).

Multiple checkbox filters return server error 500

I am trying to set up a Wordpress portfolio page with multiple checkbox filtering options. The js-code and some HTML is from MixItUp (http://codepen.io/patrickkunka/pen/iwcap).
<div class="row">
<!-- Filter categories -->
<div class="col-md-4">
<form class="controls" id="Filters">
<?php
$count1 = 0;
// all products of category with sortable
function enc8($c){ return utf8_encode($c); }
$terms1 = get_terms( product_group );
$count1 = count($terms1);
echo '<fieldset>';
if ( $count1 > 0 ){
foreach ( $terms1 as $term1 ) {
$termname1 = strtolower($term1->name);
$termname1 = str_replace(array(enc8('ä'),enc8('Ä'),enc8('ö'),enc8('Ö'),enc8('ü'),enc8('Ü'),enc8('ß'),' & ',' '),array('ae','Ae','oe','Oe','ue','Ue','ss','-','-'),$termname1);
echo '<div class="checkbox"><input type="checkbox" value=".'.$termname1.'"/><label> '.$term1->name.'</label></div>';
}
}
echo '</fieldset>';
?>
<a class="btn btn-small btn-default" id="Reset">Reset</a>
</form>
</div>
<div class="col-md-4">
<form class="controls" id="Filters">
<?php
$count2 = 0;
// all products of category with sortable
function enc8($c){ return utf8_encode($c); }
$terms2 = get_terms( product_category );
$count2 = count($terms2);
echo '<fieldset>';
if ( $count2 > 0 ){
foreach ( $terms2 as $term2 ) {
$termname2 = strtolower($term2->name);
$termname2 = str_replace(array(enc8('ä'),enc8('Ä'),enc8('ö'),enc8('Ö'),enc8('ü'),enc8('Ü'),enc8('ß'),' & ',' '),array('ae','Ae','oe','Oe','ue','Ue','ss','-','-'),$termname2);
echo '<div class="checkbox"><input type="checkbox" value=".'.$termname2.'"/><label> '.$term2->name.'</label></div>';
}
}
echo '</fieldset>';
?>
<a class="btn btn-small btn-default" id="Reset">Reset</a>
</form>
</div>
The first taxonomy filter (product_group) works just fine. However, when I add the second one (product_category) the page partly crashes and Chrome returns the following error message: Failed to load resource: the server responded with a status of 500 (Internal Server Error).
The HTML output looks like this:
<div class="col-md-4">
<form class="controls" id="Filters">
<fieldset>
<div class="checkbox">
<input type="checkbox" value=".class01"><label> Class01</label>
</div>
<div class="checkbox">
<input type="checkbox" value=".class02"><label> Class02</label>
</div>
<div class="checkbox">
<input type="checkbox" value=".class03"><label> Class03</label>
</div>
</fieldset>
<a class="btn btn-small btn-default" id="Reset">Reset</a>
</form>
</div>
<div class="col-md-4">
<form class="controls" id="Filters">
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/
Page Caching using disk: enhanced (User is logged in)
Served from: mydomain.org # 2016-02-21 17:03:37 by W3 Total Cache -->
</form>
</div>
Does anyone have an idea what the problem is?
Finally, I figured it out. The problem was that the following function
function enc8($c){ return utf8_encode($c); }
was twice in the code. Combining the two filters to a single function and a bit of renaming some variables was the solution:
<form class="controls" id="Filters">
<?php
$countgroups = 0;
$countcats = 0;
function enc8($c){ return utf8_encode($c); }
$groups = get_terms( product_group );
$countgroups = count($groups);
$cats = get_terms( product_category );
$countcats = count($cats);
echo '<fieldset class="groups"><h4>Produktgruppen</h4>';
if ( $countgroups > 0 ){
foreach ( $groups as $group ) {
$groupname = strtolower($group->name);
$groupname = str_replace(array(enc8('ä'),enc8('Ä'),enc8('ö'),enc8('Ö'),enc8('ü'),enc8('Ü'),enc8('ß'),' & ',' '),array('ae','Ae','oe','Oe','ue','Ue','ss','-','-'),$groupname);
echo '<div class="checkbox"><input type="checkbox" value=".'.$groupname.'"/><label>'.$group->name.'</label></div>';
}
}
echo '</fieldset>';
echo '<fieldset class="cats"><h4>Produktkategorien</h4>';
if ( $countcats > 0 ){
foreach ( $cats as $cat ) {
$catname = strtolower($cat->name);
$catname = str_replace(array(enc8('ä'),enc8('Ä'),enc8('ö'),enc8('Ö'),enc8('ü'),enc8('Ü'),enc8('ß'),' & ',' '),array('ae','Ae','oe','Oe','ue','Ue','ss','-','-'),$catname);
echo '<div class="checkbox"><input type="checkbox" value=".'.$catname.'"/><label>'.$cat->name.'</label></div>';
}
}
echo '</fieldset>';
?>
<a class="btn btn-small btn-default" id="Reset">Reset</a>
</form>
Works like a charm now :)

hide or remove checkbox which is on colorbox popup after selected in dropdown

I have dropdown list and checkbox popup(colorbox popup) list in which data comes from complaint.csv file.
complaint.csv File
1,complaint type 1
2,complaint type 2
3,complaint type 3
etc...
I want to hide/remove checkbox from the popup checkbox list when item is selected from dropdown. e.g. if 'complaint type 1' is selected from dropdown then 'complaint type 1' from checkbox list should be removed/hide.
Here is some code.
PHP code:
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Chief Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<select name="Language.PrimarySpoken" ng-hide="showAddAnswer"
ng-model="question.response.value"
ng-options="a.text as a.getText() for a in question.answers.items"
id="Language.PrimarySpoken" ng-value="a.text" class="input-wide"
ng-class="{error:hasError()}" onchange="changeEventHandler(event);">
<option class="hidden" disabled="disabled" value=""></option>
<?php
$file_handle = fopen("../complaint.csv", "r");
while (!feof($file_handle)) {
$lines_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach ( $lines_of_text as $line_of_text):
?>
<option value="<?php print $line_of_text[1]; ?>">
<?php print $line_of_text[1]; ?></option>
<?php endforeach; ?>
</select>
<br/> <br/>
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Additional Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<div class="form-row added ng-binding" ng-bind-html="question.getText()" id="text" ></div>
<div class="form-row addlink ng-binding"
ng-bind-html="question.getText()">
<em><a class='inline' href="#inline_content">+ Add/Edit</a></em>
</div>
<div style='display:none'>
<div id='inline_content' style='padding:25px; background:#fff; font-size: 17px;'>
<form action="" id="popup_form">
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('../complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[1].'" id="checkbox'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
?>
<br/>
<input type="submit" name="submit" id="update"
class="button button-orange"
style="width: 90px; margin-top: 450px; margin-left:-1062px;"
value="Update">
<input type="submit" name="cancel" id="cancel"
class="button button-orange"
style="width: 90px; background-color:#36606e;"
value="Cancel">
</form>
</div>
</div>
JS code
<script type="text/javascript">
function changeEventHandler(event) {
$('.inline').colorbox({onLoad: function() {
// alert('You have ' + event.target.value + ' complaint.');
$('input[type=checkbox][value=' + event.target.value + ']').parent().hide();
}});
}
</script>
In above JS code I am getting alert of selected value from dropdown (the line of alert which is commented) but the checkbox item having that selected value is not removing somehow.(for this line $('input[type=checkbox][value=' + event.target.value + ']').parent().hide(); , I am getting just loading icon on popup)
Can anyone please tell me how should I do that?
Note: I am reading data from complaint.csv file for both dropdown list and checkbox popup list in php as shown in above code.
make following changes and check
$('input[type=checkbox][value="' + event.target.value+ '"]').parent().hide();

Concatenate variable into radio button selector

I am trying to find the value of a checked radio button. I am concatenating the variable 'flagName' into the input selector, and it keeps returning undefined. Here is my JQuery:
function filterProjects (searchInput) {
var filter = $(searchInput).val(), count = 0;
var $projects = $(".ProjectDisplay");
$projects.show();
$projects.each(function () {
var $currentProject = $(this);
var projectFlags = $(this).data();
for (var flagName in projectFlags) {
var flagValue = projectFlags[flagName];
var checkedInputValue = $("input[name='" + flagName + "']:checked", "#flagSearchForm").val();
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
}
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
});
}
I am trying to find the value of checkedInputValue. flagName and flagValue both return what they are supposed to. In the HTML, I have a form that loops through a PHP array to create multiple fieldsets that have three radio buttons each. Here is part of my HTML where the form is:
<form id="flagSearchForm" name="flagForm">
<div class="grid-unit grid-unit-9-14">
<h4>Search by Flag Value</h4>
<div class="flagSearch">
<div class="wrapper grids">
<?php
$flag_names = array("hasBib", "hasChoice", "hasEbooks", "hasFrbr", "hasLcd","hasLtp", "hasNlm", "hasPeers", "includeDewey", "includeGovtDocs", "includeNonBooks", "includeOpacUrl", "includeProtection", "includeScores"); ?>
<?php foreach ($flag_names as $i=>$flag_name):
?>
<div class="flagfields">
<div class="grid-unit grid-unit-3-14">
<fieldset>
<span class="flagName"><?php echo $flag_name; ?></span>
<input type="button" value="N/A" class="tri-state ignore" id="<?php echo $flag_name; ?>"/>
<input type="radio" name="<?php echo $flag_name; ?>" value="ignore" id="<?php echo $flag_name; ?>-ignore" class="radio-button" checked><label for="<?php echo $flag_name; ?>-ignore">Ignore</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="yes" id="<?php echo $flag_name; ?>-yes" class="radio-button"><label for="<?php echo $flag_name; ?>-yes">Yes</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="no" id="<?php echo $flag_name; ?>-no" class="radio-button"><label for="<?php echo $flag_name; ?>-no">No</label>
</fieldset>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<input type="submit" value="submit" class="flagSearchSubmit">
</div>
Is my syntax for checkedInputValue wrong?
I'm not sure what your filter/regex was so that will need to be completed. This logs all the selected inputs.
Here is a fiddle: https://jsfiddle.net/c4qbywrt/7/
function filterProjects(searchInput) {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var $currentProject = $(this);
var checkedInputValue = $(this).val();
var flagValue = '0'; // Not sure what is setting this
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
var filter = '';
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
}
});
}
$("#searchProjects").keyup(function () {
filterProjects($(this));
});
$("#flagSearchForm").submit(function (event) {
event.preventDefault();
filterProjects($("#searchProjects"));
});

Categories