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;
});
Related
I have an select input field, and i have an onchange function. The table shows the value on the selected value, if nothing is selected, it should show all data. I want to know if it possible to get the value of that select field before the onchange happens? So, the value before the change.
I looked on the internet, but nothing helps.
This is my current code:
HTML
<form action="#" method="get">
<div class="form-group" style="max-width: 300px; width: 98%;">
<select name="status" id="status" class="form-control" onchange="getProjectsByStatus(this.value)">
<option value="">Select a status</option>
<?php foreach ($status as $stat) { ?>
<option value="<?php echo $stat['status_id']; ?>"><?php echo $stat['status']; ?></option>
<?php } ?>
</select>
</div>
</form>
Javasscript
function getProjectByStatus(value) {
var current = document.getElementById('project-status').value;
if (value == "") {
document.getElementById('project-status').innerText = this.current;
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('project-status').innerHTML = this.responseText;
}
};
xmlhttp.open('GET', 'getProjectsByStatus.php?status='+value, true);
xmlhttp.send();
}
}
I would recommend, not to use html attributes like 'onchange'. Functions, used by those attributes must be in the global namespace.
This should be prevented. Instead, you should register the event from your javascript code. The following example uses jquery.
The code would be different, if you use vanilla js or another framework.
$(function() {
var $status = $('#status');
var previousValue = $status.val();
$status.change(function() {
var newValue = $status.val();
// here your logic
});
});
With such approach, you can store the initial state of the input and access it, if the value of the select field is changed. Additionally you prevent your app from writing into the global namespace.
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
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);
}
});
I get users from mysql query. I show this users into table and add a HTML into php file to all users to change a value:
...
do {
echo "<td > <a>".$row["username"]."</a> </td> \n";
echo "<td > <a>".$row["name"]."</a> </td> \n";
echo "<td > <select id='sel'> <option value='admin'>Admin</option> <option value='user'>User</option> </select> </td> \n";
} while ($row = mysql_fetch_array($result));
echo "</tbody></table> \n";
...
How can I get the option selected??
I'm trying get this in javascript but always get the same first value, independet value selected.
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
}
Thanks!
Use the jquery .change function.
Fiddle :- https://jsfiddle.net/a2abaL44/1/
<script type="text/javascript">
$("#sel").change(function(){
var selectVal = $(this).val();
})
</script>
https://api.jquery.com/change/
Because your loop will be executed multiple times (once for each user in the database), you will have many <select> elements with the same ID. You cannot have the same ID given to many different elements, and this is why your JavaScript is only returning the value of the first <select>.
If you tell me what you are needing the selected value for, I can update the answer further.
Your code is fine, Change your select to <select id="sel" onchange="myFunction();">
<script type="text/javascript">
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
alert(strUser);
}
</script>
My list is generated via php:
<input name="txt_name" list="emp_names" autocomplete="off" id="txt_name" class="textbox" onchange="getID(emp_names.text);"/>
<datalist id="emp_names">
<?php
$host = "localhost";
$user = "root";
$pass = "mark";
$db = "payrolldb";
$cons = mysql_connect($host,$user,$pass);
mysql_select_db($db,$cons);
//query start
$query = "SELECT ID_Employee, CONCAT(LastName,', ',FirstName) AS Name, Department FROM tbl_employeeInfo;";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['Name']."'>".$row['ID_Employee']."</option>\n";
}
?>
</datalist>
And it shows up like this.
Each of the options has a text value, which is "15" from the image.
the value of the option itself is "Mehta, Jack"
I wanted to know how to get the text value and to pass it from a javascript function.
I tried using an onchange method in both the input and the datalist tag.
But it says Cannot ready property text of 'undefined'.
Try:
// get the input element and attach event listener to it
document.getElementById("txt_name").addEventListener("keyup", function (event) {
if (event.which === 13) { // if enter/return key is pressed
alert(this.value); // get the value
}
}, false);
This is the best way I have found to do this using JQuery
var selection = $("#txt_name").val();
var text = $("#emp_names option").filter(function () { return this.value == selection; }).text();
You have to put the function on the oninput event of the input NOT the datalist. This will fire as soon as you pick the selection. if you use onchange event it will only fire after you lose focus or the blur() happens.
There is no straight way to get datalist option text in javascript
You can add one more attribute id and put that text value there and get the result like below
HTML
<input list="emp_names" id="txt_name">
<datalist id="emp_names">
<option value="Mehta, Jack1" id="15">15</option>
<option value="Mehta, Jack2" id="16">16</option>
<option value="Mehta, Jack3" id="17">17</option>
<option value="Mehta, Jack4" id="18">18</option>
<option value="Mehta, Jack5" id="19">19</option>
</datalist>
<input type="button" onclick="alertTheSelectedValue()" value="submit">
JS
var alertTheSelectedValue = function() {
var val = document.getElementById('txt_name').value;
var text = $('#emp_names').find('option[value="' + val + '"]').attr('id');
alert(text);
}
Demo: http://plnkr.co/edit/fJ8aT1PsbftWV8Q6d0tZ?p=preview