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"));
});
Related
I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced
I have a checkbox group where I need to disable the required validation check on page load.
I have tried like below, but the "required" check still appears.
Below is the div that appears from the browser console as is:
<div class="key-class-div">Key :
<select class="targetSelect" name="Keys[]" id="key_H3UKE01hlI" rel="H3UKE01hlI" onchange="return getPreferenceValues(this, 'H3UKE01hlI');">
<option value="">Choose one</option>
<option value="25/checkbox//" alt="25">Gender</option>
<option value="26/checkbox//" alt="26" selected="">Marital Status</option>
<option value="27/radio//" alt="27">Education Status</option>
<option value="28/checkbox//" alt="28">Employment Status</option>
<option value="29/checkbox//" alt="29">Professional Status</option>
<option value="30/checkbox//" alt="30">Interests</option>
<option value="31/checkbox//" alt="31">Age</option>
<option value="40/date/range/" alt="40">DOB</option>
<option value="52/text//" alt="52">Home City/Town</option>
<option value="53/text//" alt="53">Year of Birth</option>
</select>
<span style="color:red;" class="key-error-class" id="key_error_H3UKE01hlI"></span>
<span id="valueResponse_H3UKE01hlI" class="valueResponse-class">
Value :
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" checked="" id="value_H3UKE01hlI" value="211">Single</label>
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" id="value_H3UKE01hlI" value="212">Married</label>
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" id="value_H3UKE01hlI" value="0">Any</label>
<span style="color:red;" class="value-error-class" id="value_error_H3UKE01hlI">Required</span>
</span>
HTML : (Have mentioned "problem here below")
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return optinUpdateUsersFun()
}
else if($('input[name=target_criteria]:checked').val() == 'registered_users')
{
return registeredUsersUpdateFun()
}
else if($('input[name=target_criteria]:checked').val() == 'preference_based_users')
{
return validateForm() //Problem here
}
else{
return false;
}
">
JS function which gets called on click of button.
This is where validation is checked as "Required"
(have pasted entire function- so its big)
validateForm = function()
{
console.log('not---');
var validation = true;
var Keys = $('select[name="Keys[]"]');
jQuery.each(Keys,function( key, object )
{
var preferenceData = $("#"+object.id).find('option:selected').attr("value");
var keyId = $("#"+object.id).attr("rel");
$("#key_error_"+keyId).html("");
$("#value_error_"+keyId).html("");
$("#startValue_error_"+keyId).html("");
$("#endValue_error_"+keyId).html("");
var res = preferenceData.split("/");
var preferenceId = res[0];
var dataType = res[1];
var EqualRange = res[2];
var SingleMultiple = res[3];
var value = $(this).val();
if (value.length ==0)
{
$("#key_error_"+keyId).html("Required");
validation = false;
}
var arrayDataTypesOne = [ "number", "date", "time", "text", "dropdown" ];
var arrayDataTypestwo = [ "checkbox", "radio" ];
if (jQuery.inArray(dataType, arrayDataTypesOne) > -1)
{
if (EqualRange == 'equal' || EqualRange == '')
{
if (SingleMultiple == "single")
{
preferenceValue = jQuery("#value_"+keyId).val();
if (preferenceValue.length == 0)
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}else if (SingleMultiple == "multiple")
{
preferenceValue = jQuery("#value_"+keyId).val();
if (preferenceValue.length == 0)
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}
}else if (EqualRange == 'range')
{
StartValue = jQuery("#startValue_"+keyId).val();
EndValue = jQuery("#endValue_"+keyId).val();
if (StartValue.length == 0)
{
$("#startValue_error_"+keyId).html("Required");
validation = false;
}
if (EndValue.length == 0)
{
$("#endValue_error_"+keyId).html("Required");
validation = false;
}
}
}else if (jQuery.inArray(dataType, arrayDataTypestwo) > -1)
{
Values = $('input[name="Values['+preferenceId+'][]"]');
if(!Values.is(':checked'))
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}
//alert(dataType+'/'+SingleMultiple);
});
// alert(validation);return false;
if (validation == false )
{
return false;
}else{
return true;
}
}
PHP phtml Code for the same (part of the code- for comparison with browser console)
<div class="key-class-div">Key :
<select class="targetSelect" name="Keys[]" id="key_<?php echo $randomString; ?>" class="key-class" rel="<?php echo $randomString; ?>" onchange="return getPreferenceValues(this, '<?php echo $randomString; ?>');">
<option value="">Choose one</option>
<?php foreach ($AdminpreferncesData as $value) { ?>
<option value="<?php echo $value['id'] . '/' . $value['FieldType'] . '/' . $value['EqualRange'] . '/' . $value['SingleMultiple']; ?>" alt="<?php echo $value['id']; ?>" <?php if ($value['id'] == $Fields['PreferenceFieldID']) { ?> selected <?php } ?> ><?php echo $value['FieldName']; ?></option>
<?php } ?>
</select>
<span style="color:red;" class="key-error-class" id="key_error_<?php echo $randomString; ?>" ></span>
<span id="valueResponse_<?php echo $randomString; ?>" class="valueResponse-class">
<?php
$Options = explode(',', $Fields['options']);
$OptionIds = explode(',', $Fields['optionIds']);
$expOptions = array_combine($OptionIds, $Options);
$divid = $randomString;
?>
<?php if ($Fields['FieldType'] == "text") { ?>
Value :<label id="">
<input class="targetSetting" type="text" name="Values[<?php echo $Fields['PreferenceFieldID']; ?>][]" id="value_<?php echo $divid; ?>" value="<?php echo $Fields['KeyValue']; ?>">
<span style="color:red;" class="value-error-class" id="value_error_<?php echo $divid; ?>" ></span>
</label>
...
This is how i am trying to disable the 'required' attribute on page load using jQuery.
$(document).ready(function() {
//Tried using this
$('.targetSetting').removeAttr('required'); //not working
$('.valueResponse-class').prop('disabled',true); //not working
});
I want to disable required attribute for all checkboxes/radiobuttons on click of Update button (update button code's HTML have posted above)
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);
I'm trying to get a list of radio inputs from a form that are grouped by their names, and they all have different names. I'm trying to create an array with them, if they are checked then append a 1 to the array, otherwise append a 0. None of the alert boxes pop up, so I assume that the function processDataForFinalization doesn't get called.
I didn't know if something was wrong with how I'm appending to the array. Or if it's a bigger error than that.
Thanks in advance.
EDIT4 Here is the updateBallot.php code
TwoResults.txt looks like:
0 0 0 0 0 0 0 0
3 4 1
<?php
$name = $_POST['name'];
$points = $_POST['points']; //array of user vote
echo $points;
$txt_file = file_get_contents($name.'Results.txt');
$rows = explode("\n", $txt_file); // rows-array separated by new line
foreach($rows as $row => $data)
{
$row_datas = explode(' ',$data);
}
$goods = $row_datas[0];
$goodies = $row_datas[1];
$newArr = [];
for($j=0;$j<count($points);$j++) {
$newArr[$j] = $goods[$j] + $points[$j];
}
$newText = "";
foreach($newArr as $nArr => $nData) {
$newText .= $nData." ";
}
$newText .= "\n";
$secondNewArr = [];
$sizeOfBottom = count($goodies);
for($k=0;$k<$sizeOfBottom;$k++) {
$secondNewArr[$k] = $goodies[$k];
}
foreach($secondNewArr as $neArr => $neData) {
$newText .= $neData." ";
}
$myFile = fopen($txt_file,"w+");
fwrite($myFile, $newText);
fclose($myFile);
?>
EDIT3 Here is the output HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="20">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="Array">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
</div>
<script>
var numQs = 1;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
</div>
<script>
var numQs = 2;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input2" value="1">
a <br>
</div>
<script>
var numQs = 3;
</script>
<br><br><br>
<div class="submit">
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</div>
</form>
EDIT2 Here is the HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="<?php echo $arr;?>">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<?php
if (file_exists($name.'.txt')) {
if($type==1) {
$inputType = "checkbox";
} else {
$inputType = "radio";
}
$txt_file = file_get_contents($name.'.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
$vals = 0;
foreach($rows as $row => $data)
{
$arrCount = 0; // number of elements in array
echo "<div id='ballotElement'>";
$row_data = explode('^',$data);
$info[$row]['questions'] = $row_data[0];
$info[$row]['answers'] = $row_data[1];
echo "<h4><u>".$info[$row]['questions'] . "</u></h4>";
//echo $info[$row]['answers'] . "<br>";
$lines = explode("~",$info[$row]['answers']);
foreach($lines as $line => $lData) {
$answers[$row][$line] = $lData;
if($answers[$row][$line] !== "") {
$arrCount++;
?>
<input type="<?php echo $inputType; ?>" name="input<?php echo $row; ?>" value="1">
<?php echo $answers[$row][$line]; ?>
<br>
<?php }
$vals++;
}
if($writeIn == "y") {
$arrCount++; ?>
<input type="text" name="writeIn<?php echo $row; ?>" placeholder="Write in">
<?php
}
echo "</div>";
array_push($arr, $arrCount);
?>
<script>
var numQs = <?php echo count($arr); ?>;
</script>
<?php
}
} else {
header('Location: error.php');
}
echo "<br><br><br>";
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</form>
EDIT getActualData() is called from getData()
Here is getData(), this function works, so I'm not sure why the getActualData() doesn't work since they are basically the same thing.
function getData() {
var parts = 0;
for(var i=0; i<numQs; i++){
var checked = false;
var inp = document.getElementsByName('input'+i);
for(var j=0; j<inp.length && checked == false; j++){
if(inp[j].checked) {
checked = true;
parts++;
}
}
}
if(parts != numQs){
window.alert('Please vote for at least one candidate per race.');
return false;
} else {
window.alert('Okay');
getActualData();
//return true;
}
}
function processDataForFinalization() {
$.ajax({
url: 'updateBallot.php',
type: 'post',
data: {"points" : val, "name":name},
success: function(data) {
// Do something with data that came back.
window.alert(data);
//return true;
}
});
}
var val = [];
function getActualData() {
for(var k=0;k<numQs;k++) {
var inpu = document.getElementsByName('input'+k);
for(var jk=0;jk<inpu.length;jk++) {
window.alert('almost there');
if(inpu[jk].checked) {
window.alert('hello');
val.array_push(1);
window.alert(val.length);
} else {
val.array_push(0);
}
}
}
processDataForFinalization();
}
I want to check if the value of the select field is some value and if it is, it needs to echo some text.
I use this code for input box in the form:
<li>
<div class="input-box">
<strong><?php echo $this->__('Would you recommend this product to a friend?') ?></strong>
<?php foreach ( $this->getOptions() as $option ): ?>
<label class="recommend">
<input type="radio" name="recommend" id="recommend_field
<?php echo $option['value'] ?>" class="radio-gender" value="
<?php echo $option['value'] ?>"
<?php if ($option['value'] == $value)
echo ' checked="checked"' ?> >
<?php echo $this->__($option['label']) ?></input>
</label>
<?php endforeach ?>
</div>
</li>
And I currently echo the entire value of the input box with this line:
<div id="reviewwriter">
<span class="recommendation">
<?php echo $this->getAnswer() ?>
</span>
</div>
Code is loaded by this php:
public function confRecommendItemsArray()
{
$resArray = array();
if (Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field1')) {
$resArray[] = array(
'value' => 1,
'label' => Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field1')
);
}
if (Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field2')) {
$resArray[] = array(
'value' => 2,
'label' => Mage::getStoreConfig('advancedreviews/recommend_options/recommend_field2')
);
}
And
class AW_AdvancedReviews_Block_Recommend_Field extends Mage_Core_Block_Template
{
public function canShow()
{
return (Mage::helper('advancedreviews')->confShowRecommend()
&& count(Mage::helper('advancedreviews')->confRecommendItemsArray()));
}
public function getOptions()
{
return Mage::helper('advancedreviews')->confRecommendItemsArray();
}
}
The values of the select field are
1. Yes
2. No
I want to check if value is Yes and if so echo 'Value is Yes'.
And if value is No than echo ''.
See also this JSFiddle: http://jsfiddle.net/wL3xu9d7/1/
But I do not know why it is not working.
How can I achieve that?
i hope this solution you want...
<li>
<div class="input-box">
<strong><?php echo $this->__('Would you recommend this product to a friend?') ?></strong>
<?php foreach ( $this->getOptions() as $option ): ?>
<label class="recommend">
<input type="radio" name="recommend" id="recommend_field<?php echo $option['value'] ?>" class="radio-gender" value="<?php echo $option['value'] ?>"<?php if ($option['value'] == $value) echo ' checked="checked"' ?>><?php echo $this->__($option['label']) ?></input>
</label>
<?php endforeach ?>
</div>
</li>
add hidden field on answer
<div id="reviewwriter">
<span class="recommendation" id="reviewwriteranswer">
<?php echo $this->getAnswer() ?>
</span>
</div>
<script>
$$(".radio-gender").each(function(el) {
el.observe("click", function(event) {
if(el.checked)
{
sub = $('reviewwriteranswer').value;
sub ==sub =.trim();
if(el.value==sub)
{
$('reviewwriteranswer').update('value is yes');
}else {
$('reviewwriteranswer').update('value is No');
}
}
});
});
</script>
<scrip>
var allElements = document.body.getElementsByTagName("*");
for(var i = 0; i < allElements.length; i++) {
var text = allElements[i].innerHTML;
text=text.trim();
if (text == 'Yes') {
allElements[i].innerHTML = "Value is Yes";
}
if (text == 'No') {
allElements[i].innerHTML = "Value is No";
}
}
</scrip>