multiselect filter using javascript - javascript

I have option tag and it works fine with single filter and I want to make it multi select....following is my code:-
$('#version_no').change(function () {
var version_no = $('#version_no').val();
if (version_no != null) {
showAll(version_no);
} else {
showAll();
}
});
showAll() is a function that returns data after filtering. if no filter is selected then everything is shown.
following is the view code:-
<select multiple="multiple" style="margin-top:15px;" name="version_no" id="version_no">
<option value="">Select Version No</option>
<?php if (count($get_version_no)): ?>
<?php foreach ($get_version_no as $version): ?>
<option value=<?php echo $version->version_no; ?>><?php echo $version->version_no; ?></option>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
$get_version_no is generating the dropdown value like 1,1.1,1.2 etc.....
SO I want to make it multi select any help will be appreciated. I'm using codeigniter 3.

You need to make version_no array in name for multiple select
<select multiple="multiple" style="margin-top:15px;" name="version_no[]" id="version_no">
In jquery
var version_no= [];
$.each($("#version_no option:selected"), function(){
version_no.push($(this).val());
});
var version = version_no.join(", ");
version will be the string with all selected values seperated by comma

Your Javascript code just needs to be refactored so that version_no is an array instead of a single value. You can use the ':selected' selector to get the selected options.
(see https://api.jquery.com/selected-selector/)
You will also need to refactor the showAll() function so that it parses an array instead of a single value. I would also have the showAll() function perform null checks instead of doing that if...then/else.

Related

Select tag HTML dynamic javaScript PHP

Hello I want to achieve is to make "Select Form HTML" dynamic using JavaScript, What I mean by that is I expect every time I select a dropdown must be selected the value that I set to that tag.
The data from tag is from database I loop the data using php
ex. 1 src: Get selected value/text from Select on change
This example is 100% working correct but what I need is not to get the value but to assign like sample below next example 2
function handleSelectChange(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
<select onchange="handleSelectChange(event)">
<option value="1">one</option>
<option value="2">two</option>
</select>
ex 2 Those function will alert or run everytime I select/Click each of them F1 or F2
<table>
<tr>
<td onclick="myFunction1()">F1</td>
<td onclick="myFunction2()">F2</td>
</tr>
</table>
<script>
// Function 1 will run when I click the F1
function myFunction1() { alert('myFunction1'); }
// Function 2 will run when I click the F2
function myFunction2() { alert('myFunction2'); }
In example 1 As you can see the first example select form html will grab the the value of option tag, right?.
Now In example number 2 it will run the function when I click each of the F1 or F2
So what I need to the program is pass a value from my database to my javaScript function and run it like in alert or example 1 but in "Select tag" HTML version
ex. 3 Here's my query
<form action="">
<select name="customers" id="myId" class="form-control">
<option value="">Select a customer:</option>
<?php
$user_id = 1;
$sql = "SELECT * FROM `myTable` WHERE user_id = '$user_id' Order by create_at DESC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{ ?>
<!-- appsFunction('<?php echo $row['colName2']; ?>') << will be the value that should run in console.log -->
<option value="<?php echo $row['id']; ?>" onclick="appsFunction('<?php echo $row['colName2']; ?>')"><?php echo $row['colName1']; ?></option>
<?php }
} else { return false; }
?>
</select>
</form>
ex. 3 part 2 javascript
<script>
function appsFunction(passVar) {
colose.log(passVar);
}
</script>
As you can see in my first example a "Select Tag" HTML when I select dropdown it returns to me a value right?, in second example when I click F1 or F2 it will run the function then return alert, What I need here is When I select the dropdown it will accept the value I pass in function "appsFunction(passVar)" appsFunction('<?php echo $row['colName2']; ?>') from select tag which the value is from my database.. so I need help idea how to do that properly..
NOTE: The function must be run when I select the dropdown, the function must be accept the value I set which from my database it's like totally example number 2 but in Select tag HTML version not just text or html table.
Thanks in advance for solving my problem.
If you register an event handler on the select element itself that listens for change events you will be able to process the selected OPTION and access any value/property associated with it. You cannot assign an event handler directly to an OPTION element as you are trying to do here. You can add as many dataset attributes as you need to the OPTION elements however which you can easily access in the Javascript event handler.
If the value you pass into the SQL statement is to be dynamic ( from a GET or POST request most usually ) you really need to use a Prepared Statement to help mitigate SQL Injection attacks.
As your select menu is making use of only 3 columns from the mytable table you should limit the returned fields to those columns which in turns helps when using a Prepared Statement as you can easily assign the results as variables.
<form name='geronimo'>
<select name="customers" class="form-control">
<option selected hidden disabled>Select a customer:
<?php
$user_id = 1;
$sql="select `id`, `colName1`, `colName2` from `mytable` where user_id = ? order by create_at desc";
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('s',$user_id);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($id,$col1,$col2);
while( $stmt->fetch() ){
printf('<option value="%s" data-col="%s">%s', $id, $col2, $col1 );
}
$stmt->free_result();
$stmt->close();
}
?>
</select>
</form>
<script>
document.forms.geronimo.customers.addEventListener('change',function(e){
let id=this.value;
let col2=this.dataset.col;
let col1=this.options[this.options.selectedIndex].text;
alert( id + ' ' + col2 + ' ' + col1 )
});
</script>

Operation with Javascript with a variable from a form in PHP

I'm new on this site, so please don't judge me. ;)
Btw, my question is about how can i call varible(montoUti) from this form and make an operation with javascript by the moment when I select an option.
I've been reading that i can use a function called "onchange" but I'm not sure how it works.
I have this code in php that is calles FEvaluacion.php
`
<select class="col-lg-12" name="montoUti" onchange="myFunction()">
<option value="<?php echo $montoUti?>">------</option>
<?php
require("connect_db.php");
$query = $mysqli -> query ("SELECT montoUti FROM utilidad");
while ($valores = mysqli_fetch_array($query))
{
echo '<option
value="'.$valores[montoUti].'">'.$valores[montoUti].'</option>';
}
?>
</select>'
And here we have the another code in javascript called operacion.php
`<script>
function myFunction()
{
var bmontoUti = document.getElementById("montoUti").value;
if(prom>=60 && prom<=80)
{
utilidad=(prom/bmontoUti)*5;
document.formulario.utilidad.value=utilidad;
}
}
</script>'
However, I really hope you can help me.
Thanks
Regards!
to use document.getElementById("montoUti").value; you need to set an id in your <select> you are currently just setting a name try
<select class="col-lg-12" id="montoUti" name="montoUti" onchange="myFunction()">

Filter Dropdown Based on Other Dropdown Selection

I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
This is the JavaScript that I have so far, however, if I do a console.log(classN), all that it is doing is just logging all of the dates. It doesn't actually filter anything:
$(document).ready(function () {
var allOptions = $('#date option')
$('#collector').change(function () {
$('#date option').remove();
var classN = $('#collector option:selected').prop('class');
var opts = allOptions.filter('.' + classN);
console.log(opts);
$.each(opts, function (i, j) {
$(j).appendTo('#date');
});
});
});
jquery can't run php on the page once it is loaded. You could use ajax, running the query to get the second set of options from another file.
<select id="collector">
<?php //code to generate initial collector options ?>
</select>
<select id="date">
<option>--Bill Date--</option>
</select>
In your jquery, target the first dropdown and then use load() to call a php file
$(document).ready(function(){
$("#collector").on('change', function(){
filterItems(this.value);
});
});
function filterItems(value){
var destination = "#date";
var url = "path/to/filterCode.php?v="+value;
$(destination).load(url);
});
In the filterCode php file, get the value selected by the user
$selectedCollector = $_GET['v'];
Then use $selectedCollector to query your database and get the appropriate date options.
Then, inside your results loop:
echo '<option class="'.$date['Date'].'" value="'.$date['Date'].'">'.$date['Date'].'</option>';
The load() will take these echoed options and put them into #date.
I think you need to populate #date drop-down based on #collector drop-down value, according to me best option is ajax.
here some basic example,
<select id="collector">
<option value=""></option>
</select>
jut think this as your #collector drop-down there will be some options based on your data. Now you need to populate #date drop-down,
<select id="collector">
<option value=""></option>
</select>
In page load you can load all the data if you want.
when #collector drop-down change you can send ajax request and retrieve data from database based on #collector value, like this
$("#collector").on('change', function(){
$.ajax({
type: method,
url: url,
data: data,
success: function(response) {
//populate select box
}
});
});
Below links will be helpful,
How to Use jQuery’s $.ajax() Function
Populate dropdown select with array using jQuery

dynamic disable select box with javascript

I am trying to make an html select box which dynamically disables and enables based on what the user select in a different select box... This was working fine when I used just html, but I would like to use the jQuery plugin Chosen for this, and it is not working... The main thing I need dynamic chosen to be disabled or enabled based on the onchange for the other select box. Is this possible with chosen? And how? Thanks so much.
Old Code : Working
<script>
function myDisable() {
a=1;
b=3;
for (i=1;i<3;i++){
posi=a+b*i;
document.getElementById('drop'+posi).disabled = true;
} }
</script>
New code with PHP : Not Working
<script>
function myDisable() {
a=<?php echo $angka; ?>; // a variable number for id select box
b=<?php echo $fields; ?>; // b variable number of many fields table
j=<?php echo $jp; ?>; // j variable number of select boxes that will disable
for (i=1;i<j;i++){
posi=a+b*i;
document.getElementById('drop'+posi).disabled = true;
} }
</script>
PHP select box looping +/- 50 :
<select name="modul[]" id="drop<?php echo $angka ?>" onchange="fetch_select<?php echo $random ?>(this.value); check(this); myDisable();">
<option value="0">Lanjutan</option>
<?php
include 'include/conn.php';
$select=mysql_db_query(#$db,"select nama_modul,jp from modul where nama_pelatihan='$nama_pelatihan'",#$koneksi);
while($row=mysql_fetch_array($select))
{
$jp=$row['jp'];
echo "<option value='".$row['nama_modul']."'>".$row['nama_modul']."(".$row['jp'].")</option>";
}
?>
</select>
Try executing a call to $("#form_field").trigger("chosen:updated"); after the for loop just before exiting the myDisable() function. In your case #form_field will be some selector that identifies your html select box element. Chosen might need to redraw itself to reflect the updated options and this is how we can tell it to do that.

Symfony 1.4: How I can retrieve the selected value with AJAX's function in select dependent?

In my database I have two related fields. The second field depends on the value selected in the first. The relations are:
The function I use in the form of table "conflictos_1" is:
<!--Aquí el javascript para select dependientes-->
<script type="text/javascript">
$(document).ready(function()
{
$("#conflictos1_id_sector_actividad").change(function()
{
var id_sub = $(this).val();
if(id_sub != '')
{
$.ajax
({
type: "POST",
url: '<?php echo url_for('conflictos/subsector'); ?>'+ '?id=' + id_sub,
cache: false,
data: "id_sub="+ id_sub,
success: function(data)
{
$("#conflictos1_id_subsector_actividad").html(data); // but it does not select the value of dropdown list.
}
});
}
else
{
$("#conflictos1_id_subsector_actividad").html("<option value=''>-- No se ha seleccionado subsector --</option>");
}
return false;
});
});
</script>
When I add a new record, everything works fine.
But when I edit a record, the select dependent, does not show "selected" value.
In edit mode, when I look at the field "id_subsector_actividad", the selected value should be, for example, <option value="37 " selected="selected">: This is what I see on my form when I inspect the element created with AJAX's function:
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="29 ">14.1 Meretrices</option>
<option value="30 ">Preparación de alimentos y comedor</option>
<option value="31 ">Seguridad</option>
<option value="37 ">redes sanitarias</option>
</select>
This is what I WANT to see:
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="29 ">14.1 Meretrices</option>
<option value="30 ">Preparación de alimentos y comedor</option>
<option value="31 ">Seguridad</option>
<option value="37 " selected="selected">redes sanitarias</option>
</select>
I use this function to filter records in the table "Subsector_actividad_ta8"(I work with Symfony 1.4 and Doctrine):
public function executeSubsector()
{ $id_sub = $_POST['id_sub'];
$this->subsec= Doctrine_Core::getTable('SubsectorActividadTa8') ->createQuery('a')
->where('a.id_sector = ?', $id_sub)
->execute();
}
My question is: What should I change in the AJAX's function, to display the "selected" value in the second field, when I am editing an existing record?
Maybe with something like:
$("option[value='37']").attr('selected', 'selected');
You have a similar question on: Set selected option of select box
Here the solution I encountered: I've separated the problem in two.
Case 1: New Record
I use the same JQuery function shown above in the question. With the associated function, also shown above. This case was not part of my problem
Case 2: Edit an existing record (here was my problem)
I added for 'id_subsector_actividad' in the widget the property 'table_method'=>'Subsector' associated with the function public function Subsector() (see below code).
In the partial _form.php of conflictos1, I wrote the following code for the field id_subsector_actividad:
<?php if (!$form->getObject()->isNew()): ?>
<?php echo $form['id_subsector_actividad'] ?>
<?php endif; ?>
<?php if ($form->getObject()->isNew()): ?>
<select name="conflictos1[id_subsector_actividad]" id="conflictos1_id_subsector_actividad">
<option value="" selected="selected">Seleccione sub-sector</option>
<?php endif; ?>
In the action.class.php in the conflictos1, I modified the function executeEdit, with the addition of the variable $elsector:
public function executeEdit(sfWebRequest $request)
{
global $elsector;
$this->forward404Unless($conflictos1 = Doctrine_Core::getTable('Conflictos1')->find(array($request->getParameter('id'))), sprintf('Object conflictos1 does not exist (%s).', $request->getParameter('id')));
$elsector= $conflictos1->getIdSectorActividad();
$this->form = new Conflictos1Form($conflictos1);
}
I use $elsector in the following function created in SubsectorActividadTa8Table.class.php
public function Subsector()
{
global $elsector;
if (!is_null($elsector)){
$id_sub=$elsector;
$query= Doctrine_Query::create()
->select('a.id')
->from('SubsectorActividadTa8 a')
->innerJoin('a.Conflictos1 c')
->where('a.id_sector = ?', $id_sub);
return $query->execute();
}
}
Thus, Symfony displayed on the form, the value of field named IdSubsectorActividad, not previously exhibited.
In other words, now when I'm editing a record in the table conflictos1 the field named IdSubsectorActividad shows the correct value, whereas before the form does not show any value.
Now everything works fine!.

Categories

Resources