Uncheck checkbox when certain values(php) from drop down is chosen - javascript

i need to uncheck a checkbox when a value is chosen from multi dropdown. The problem is the value is a php value which is generate from foreach.
below is the code of the javascript
$("#multi_search_filter").on('change', function () {
var val = $(this).val();
if (val === <?php"'.$row['batch_name'].'" ?>) {
$('#checkUncheckAll').prop('checked', false);
return;
}
$('#checkbox1').prop('checked', true);
});
this is the code of the PHP and HTML
<select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["batch_id"].'">'.$row["batch_name"].'</option>';
}
?>
</select>
this is the input checkbox
<input type="checkbox" id="checkUncheckAll">
I tried to search for solution but failed to do so. Appreciate any help

Related

multiselect-selected-text cannot get properly value

I have a problem selecting the selected value to show in the multiple select inputs.
Now my problem is, I am doing an update function, so the data will show in input first, like below the picture, the value (developer1, developer2, developer) are missing:
But if I continue to select another value in the multiple select function input, it cannot show previously selected value in the multiple select function input, just can show newly selected value only like the below picture:
This is my mulit-select function coding:
<div class="col-lg-6">
<div class="form-group">
<label>Ahli-ahl
<select id="<?php echo $span_mandatory; ?></label><br>hli_ahli" name="ahli_ahli" class="form-control <?php echo $class_mandatory; ?>" title="Ahli-ahli" multiple>
<?php
$sql_user = 'SELECT * FROM user where is_active=1';
$row_user = base_mysqli_select($sql_connection, $sql_user, $types, $values);
foreach ($row_user as $val_user) {
echo '<option value="' . $val_user['id'] . '">' . $val_user['name'] . '</option>';
}
?>
</select>
</div>
</div>
<script>
$(document).ready(function(){
$('#ahli_ahli').multiselect({
nonSelectedText: 'Pilih ahli-ahli',
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
buttonWidth:'100%'
});
});
</script>
This gets the selected value in the multi-select bootstrap coding:
function call_to_set_Selected(ahli_ahli) {
for (var i = 0; i < ahli_ahli.length; i++) {
//add option selected
$('option[value="' + ahli_ahli[i] + '"]', $('#ahli_ahli')).prop('selected', true);
}
//refresh mutlislect
$('#ahli_ahli').multiselect('refresh');
}
Is multi-select function bug or my code is wrong to define? Hope someone can guide me on how to solve this problem. Thanks.

How to make an validation select option using javascript

I tried to make a validation using javascript but I had some trouble if I leave the field empty it shows the message, then select an item in the list but it now shows an empty message and the action isn't executed. If I click the button twice, it will go trough
I put some code :
html :
<select name="condition[]" class="search_test col-sm-6 form-control condition" style="line-height: 34px;" oninput="InvalidCondition(this)" oninvalid="InvalidCondition(this)" required>
<option value="" selected="selected" disabled>Select Condition...</option>
<?php foreach ($condition as $c) : ?>
<option value="<?= $c; ?>"><?= $c; ?></option>
<?php endforeach ?>
</select>
Javascript :
function InvalidCondition(select) {
if (select.value === "") {
select.setCustomValidity("Please select an item");
} else {
select.setCustomValidity("");
}
}
pictures :
Do you need the else condition there?
Without seeing context, will this work:
function InvalidCondition(select) {
if (select.value === "") {
select.setCustomValidity("Please select an item");
}
}
edit:
It would help if you provided a link, or perhaps more code, maybe Codepan.
In the meantime, does this work for you:
function InvalidCondition(select) {
if (select.value === "") {
select.setCustomValidity("Please select an item");
} else {
select.setCustomValidity(`${select.value}`);
}
}

Limiting the options in a combobox, based on the selected one

I made a similar question yesterday, but couldn't come up with a solution since then, so i went and refined my code a bit to a logic that seemed more plausible to work.
However, it didn't.
I want to have only a couple of options in a combobox available to the user, depending on what option was pre-selected. Here is the Combobox:
<SELECT class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus onchange= "StatusTest(); hideField();" >
<option selected></option>
<option value="Planned" id="optionPlanned" <?php if ($row['task_status']=='Planned') echo 'selected="selected"';?>>Planned</option>
<option value="Started" id="Started" <?php if ($row['task_status']=='Started') echo 'selected="selected"';?>>Started</option>
<option value="Available" id="Available" <?php if ($row['task_status']=='Available') echo 'selected="selected"';?>>Available</option>
<option value="Finished" id="Finished" <?php if ($row['task_status']=='Finished') echo 'selected="selected"';?>>Finished</option>
<option value="Impeded" id="Impeded" <?php if ($row['task_status']=='Impeded') echo 'selected="selected"';?>>Impeded</option>
</SELECT>
For example, when "Planned" is selected, the only other available option should be "Started". So i went and made a Javascript, for a Onchange Event, like so:
function hideField(){
var e = document.getElementById("cbostatus");
var strUser = e.options[e.selectedIndex].value;
if( strUser == 'Planned' ) {
document.getElementById("Impeded").style.display = 'none';
document.getElementById("Available").style.display = 'none';
document.getElementById("Finished").style.display = 'none';
}
}
And for some reason, it is wrong. Any ideas?
(Also, i'd aprecciate if you didn't suggest using Jquery, as i have never used before and don't really have time to learn for this)
I suggest you start with an empty select, and add the options dynamically.
var e=document.getElementById("cbostatus");
var strUser = 'Planned'; // get this value from somewhere, maybe a hidden field
if( strUser == 'Planned' ) {
e.options[e.length]=new Option("Planned", "optionPlanned", true, true);
e.options[e.length]=new Option("Started", "Started");
} else if ..
Use this code.
Html
<select class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus>
<option selected></option>
</select>
jQuery
var insertoption = "";
first add options in ready function
$(document).ready(function()
{
insertoption += "<option value='Planned' id='Planned'>Planned</option>";
insertoption += "<option value='Started' id='Started'>Started</option>";
insertoption += "<option value='Available' id='Available'>Available</option>";
insertoption += "<option value='Finished' id='Finished'>Finished</option>";
insertoption += "<option value='Impeded' id='Impeded'>Impeded</option>";
$("#cbostatus").append(insertoption);
insertoption = "";
});
This is create your option
and now create onchange function
$("#cbostatus").on("change",function()
{
if($("#cbostatus").val() == "Planned")
{
$("#cbostatus").children().remove();
insertoption = "<option value='Started' id='Started'>Started</option>";
$("#cbostatus").append(insertoption);
}
});

How to call a function if checkbox checked and remove from appended list if unchecked

This is how the flow like:
I first derive the value of checkbox and pass the value to a function to trigger ajax. That ajax function return a list of data in multiple group in select box. Each time a checkbox checked, the value will be appended into the selectbox. But I want to remove the value from selectbox when checkbox unchecked.
Now, when I click on the checkbox the value is passed to the function no matter I check or uncheck. How to control here?
first script
<script>
$("input[type=checkbox]").change(function() {
var selectedval = ($(this).val());
var selectedtext =($(this).next().text());
sendtobox(selectedval);
});
</script>
second script (function)
<script>
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
}
catch(E)
{
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
function sendtobox(param)
{
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('show');
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
}
//document.getElementById("show").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+param,true);
xmlhttp.send();
}
</script>
HTML
<input type="checkbox" name="level" id="level" class="level" value="1"><label>Primary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="2"><label>Upper Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="3"><label>University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="4"><label>Lower Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="5"><label>Pre University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="6"><label>Skills/Languages</label><br/>
getuser.php
<?php
$q= intval($_GET['q']);
$con = mysqli_connect('localhost','root','','wordblend_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"test_db");
//$sql="SELECT * FROM tbl_subjects WHERE level_id = '".$q."'";
$sql="SELECT * FROM tbl_levels,tbl_subjects WHERE tbl_levels.level_id=tbl_subjects.level_id AND tbl_levels.level_id='$q'";
$result = mysqli_query($con,$sql);
?>
<?php
while($row = mysqli_fetch_array($result)) {
$levels=$row['level_name'];
$subjects= $row['subject_name'];
$subjects_id= $row['subject_id'];
?>
<optgroup label="<?php echo $levels;?>">
<option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
</optgroup>
<?php
}
?>
In onchange event, check for the checked status of the checkbox and then perform action accordingly.
$("input[type=checkbox]").change(function() {
if($(this).is(":checked")) {
var selectedval = $(this).val();
var selectedtext = $(this).next().text();
sendtobox(selectedval);
}
else {
// remove the items
}
});
Regarding removal of items, you must track which values are added for that particular checkbox. Only then you can remove those particular items.
EDIT based on comments
In your PHP code, add an identifier for the items added based on the checkbox. I'm adding the $q itself which is the checkbox value as class name.
<optgroup label="<?php echo $levels;?>" class="<?php echo $q;?>">
<option value="<?php echo $subjects_id;?>"><?php echo $subjects;?></option>
</optgroup>
Now in your jquery code:
$("input[type=checkbox]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval);
}
else {
$("optgroup."+selectedVal).remove();
}
});
Now this will remove the optgroups added by the ajax call.
Check the checked property of the checkbox.
$("input[type=checkbox]").change(function() {
var selectedval = ($(this).val());
var selectedtext =($(this).next().text());
if (this.checked) {
// do something else
} else {
sendtobox(selectedval);
}
});
Edit:
About removing, I assume you wish to undo on uncheck what you do here:
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML;
Instead of adding the response text directly, add it as a new dom element inside the show element with some unique identifier you can later use to remove it. Something like this (I use jquery since you seem to use that too in your first script, this is all doable without it of course):
var ajaxElm = $('#show');
ajaxElm.append($('<span id="uniqueidgoeshere">').append(this.responseText))
And then when you remove it refer to that id. The id should be deducible from the id (or other attributes) of the changed checkbox.

Javascript to hide selected option

I have this code to hide selected options:
function connect()
{
$(".selectbox option").show();
$(".selectbox").each(function(i) {
var obj = $(".selectbox option[value='" + $(this).val() + "']");
if($(this).val() != "") obj.hide();
});
}
function to()
{
$(".selectboxes option").show();
$(".selectboxes").each(function(i) {
var obj = $(".selectboxes option[value='" + $(this).val() + "']");
if($(this).val() != "") obj.hide();
});
}
but my problem now is that, I use PHP to generate the select tag, and in that php code i have a condition that once it sees this value it will automatically add selected=selected. but my JS would still display that variable in the drop down even though it is already selected. i tried adding:
$('.selectboxes option:selected').find("option").hide();
but it did not work. any idea on how should i solve this problem?
BTW: i forgot to mention that, the php code will generate multiple select tags with the same values that will use that function, thus when i have 3 select tags 1 will have the pre selected value and the other 2 will be null, now when i click on either 2 of those that have no values selected yet i can still see in the drop down the choice that was already pre selected in select 1, what i wanted to do is that it should be automatically hidden, with that function it will not hide it until i select other choices from the drop down. since this line:
$(".selectbox option").show();
would display all choices in the drop down, is there a condition for it to exempt "this" value?
SELECT PART:
for($z=0;$z<$rows_updatedrow;$z++)
{
?>
<select id = "sc" name = "connect_array[]" class="input-select selectbox" onchange = "connect()">
<option value = "">--Select--</option>
<?php
for($zz=0;$zz<$rows_getconnect;$zz++)
{
$data_getconnect = mysql_fetch_assoc($query_getconnect);
$field_name_getconnect[] = $data_getconnect['field_name'];
$field_display_getconnect[] = $data_getconnect['field_display'];
$field_type_getconnect[] = $data_getconnect['field_type'];
if((($field_name_getconnect[$zz] == "friends_name" && $connect == 2) || $field_type_getconnect[$zz] == "email") && $z == 0){
$selected = "selected=selected";
}else{
$selected = "";
}
?>
<option value = "<?php echo $field_name_getconnect[$zz]; ?>" <?php echo $selected; ?>><?php echo $field_display_getconnect[$zz]; ?></option>
<?php
}
?>
</select>
connect to
<br/>
<?php
}
?>
</div>
<div class = "right">
<?php
for($a=0;$a<$rows_updatedrow;$a++)
{
?>
<select name = "to_array[]" class="input-select selectboxes" onchange = "to()">
<option class = "option" value = "">--Select--</option>
<?php
for($aa=0;$aa<$rows_getto;$aa++)
{
$data_getto = mysql_fetch_assoc($query_getto);
$field_name_getto[] = $data_getto['field_name'];
$field_display_getto[] = $data_getto['field_display'];
$field_type_getto[] = $data_getto['field_type'];
if((($field_name_getto[$aa] == "friends_name" && $to == 2) || $field_type_getto[$aa] == "email") && $a == 0){
$selected = "selected=selected";
}else{
$selected = "";
}
?>
<option class = "option" value = "<?php echo $field_name_getto[$aa]; ?>" <?php echo $selected; ?>><?php echo $field_display_getto[$aa]; ?></option>
<?php
}
thank you
You already have the selected option in your selector - no need to find option - as that will return you an empty array
$('.selectboxes option:selected').hide();
// get rid of .find('option')
To exempt this value.. I'm guessing you're referring to the selected value.. you can use :not as undefined stated
$(".selectbox option:not(:selected)").show();
You can take out the inline onChange since you are using jQuery.. and bind the change event handler to the select elements on dom ready
$(function(){
$('select').change(function(){
var $sel = $('option:selected'); // get all selected options
$('option').show(); // show all options
$sel.each(function(i,v){ // loop through selected options
var $index = $(v).index(); // get index of selected option
$('select').not($(this).parent()).each(function(){ // loop through other select - not current one
if($index != 0){ // not default index
$(this).find('option').eq($index).hide(); // hide selected option in other dropdowns
}
});
});
}).change(); // <-- trigger change right away
});
http://jsfiddle.net/VE7jA/
$('.selectboxes option:selected').find("option").hide();
You are trying to find('option') inside option.. Try this
$('.selectboxes option:selected').hide();
You can also remove the element once and for all if you are using it again..
$('.selectboxes option:selected').remove();
To remove a option based on value you can try
$('.selectboxes option[value="0"]').remove() ; // Removes option with value 0
As it's been said, you're trying to find an option within an option, so you'll have to get rid of the .find call.
Apart from that, hiding <option> elements do not work cross-browser, so you'll have to remove the options instead, and add them back when necessary. There are several ways to manage that, all involving storing the full list of options in a variable (as an array, an object, or even HTML string).
Hiding option elements is not always supported. A more idiomatic approach would be to disable it.
obj.prop("disabled", true);
Or simplify it like this.
$(".selectbox option:selected").prop("disabled", true);
Or this.
$(".selectbox").each(function() {
this.options[this.selectedIndex].disabled = true;
});

Categories

Resources