I need to have a dropdownlist that contains some parameters for the url on the change event. So when you select an option from the list it will redirect you to the same page with some extra parameters to query the data. The problem is when you change dropdownlist it doesn't remember it's selected option could someone show me how to have a dropdowlist show the selected option across url changes.
<script tpye="text/javascript">
$(function() {
$('#sort_by').on('change', function(e) {
window.location.href + $(this).val();
})
})
</script>
<select id="sort_by" name="sort_by">
<option>Sort By</option>
<option value="&sort_by=title&direction=asc">Title ASC</option>
<option value="&sort_by=title&direction=desc">Title DESC</option>
<option value="&sort_by=created_date&direction=asc">Created Date ASC</option>
<option value="&sort_by=created_date&title=asc">Created Date DESC</option>
</select>
i have added an extra parameter in query string 'chosen' to make the dropdown remember its selected value.
$option[0] = array('value'=>'','title'=>'Sort By');
$option[1] = array('value'=>'?sort_by=title&direction=asc&chosen=1','title'=>'Title ASC');
$option[2] = array('value'=>'?sort_by=title&direction=desc&chosen=2','title'=>'Title DESC');
$option[3] = array('value'=>'?sort_by=created_date&direction=asc&chosen=3','title'=>'Created Date ASC');
$option[4] = array('value'=>'?sort_by=created_date&title=asc&chosen=4','title'=>'Created Date DESC');
<select id="sort_by" name="sort_by">
<?php foreach($option as $key=>$val){
$a = ""; if($_GET['chosen']==$key){$a = 'selected="selected"';}
echo '<option '.$a.' value="'.$val['value'].'">'.$val['title'].'</option>';
} ?>
</select>
Hope it might help.
Related
I have a problem, it doesn't update the value of 2 selects. The value is a numeric code and a string is stored in DB.
Here is my example in HTML:
<select id="jform_country" name="jform[country]" class="form-control required chzn-done">
<option value="">Select country...</option>
<option value="1012234" selected="selected">Name country 1</option>
<option value="1012257">Name country 2</option>
</select>
<select id="jform_city" name="jform[city]" class="form-control required chzn-done">
<option value="">Select city...</option>
<option value="1982727" selected="selected">Name city 1</option>
<option value="1982739">Name city 2</option>
</select>
I retrieve DB value with a function in php (getData). But here is my problem... I try to pass that variable from PHP to JavaScript, it seems to work correctly and I change the value of the select with jQuery. But when refreshing the page, in some cases it does not work correctly.
Here is my code in PHP and jQuery:
$data = $model->getData();
$country = $data->country;
$city = $data->city;
echo '<script>';
echo 'var selectcountry = '. json_encode($country) .';';
echo 'var selectcity = '. json_encode($city) .';';
echo '</script>';
And with jQuery I recieve those variables:
jQuery(document).ready(function () {
setTimeout(function() {
rescueValue(selectcountry, selectcity);
}, 800);
function rescueValue(selectcountry, selectcity) {
if (selectcountry != null) {
jQuery("#jform_country option:contains('"+ selectcountry +"')").attr("selected", "selected");
jQuery("#jform_country").trigger("liszt:updated");
}
if (selectcity != null) {
jQuery("#jform_city option:contains('"+ selectcity +"')").attr("selected", "selected");
jQuery("#jform_city").trigger("liszt:updated");
}
}
});
Could it be that it works asynchronously? I tried to put a setTimeout but still I don't solve it. How can I make it recover the PHP value and update it in a simple way (similar to this one)? Thanks!
It's more correct to set the value of the select, than finding the option value from the list to set it the selected attribute, which may not always work if, for example, there's already another option with the selected attribute.
You can use jquery.val to set the value directly.
jQuery(document).ready(function () {
setTimeout(function() {
rescueValue(selectcountry, selectcity);
}, 800);
function rescueValue(selectcountry, selectcity) {
if (selectcountry != null) {
jQuery("#jform_country").val(selectcountry).trigger("liszt:updated");
}
if (selectcity != null) {
jQuery("#jform_city").val(selectcity).trigger("liszt:updated");
}
}
});
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
I'm making this project on site where there are list of items and they have id and there are another set of data with the same id as the first one and they each have their id. So I want to show options by getting the id of first one to display other realtime with JQuery or JScript and PHP. My code looks like this
Categories are
1. Electronics
2. Venues
And Subcategories are for electronics
Electronics
Hardware Software
Venues
My House
Friends House
<select name="category" id="catagoryid">
<?php
$categories = selectAllData('categories');
while ($row = mysqli_fetch_assoc($categories)) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<option value='{$cat_id}'>{$cat_title}</option>";
}
?>
</select>
And the another set is here
<select name="subcategory" id="subcategory">
<?php
$subcategories = selectAllData('subcategories');
while ($row = mysqli_fetch_assoc($subcategories)) {
$cat_id = $row['cat_id'];
$sub_cat_id = $row['sub_cat_id'];
$sub_title = $row['sub_cat_title'];
echo "<option value='{$sub_cat_id}' title='{$cat_id}'>{$sub_title}</option>";
};
?>
</select>
So far I what I have tried are
$('#subcategory').change(function(event) {
var subcategory = $(this).find('option:selected').attr("title");
if (subcategory!==categoryid) {
if ($(this).find('option:selected').val()!==categoryid) {
$(this).find('option:selected').hide();
}
}
});
And other approach I have been stuck here from yesterday. I have tried getting value of selected item from JavaScript and running php. But I noticed that php loads before Jscript so there is no way to do this way. There was another approach of running Jscript inside PHP but I couldn't get the value if user selects another item.
One way is remove and store all the subcategory <option> on page load.
Then clone and filter the stored <option> and replace what is in the second select when the first is changed.
You can use classes or data attributes as filters
//remove and store subcategory options
var $subCatOpts = $('#subcategory option').detach();
$('#catagoryid').change(function() {
var catId = this.value;
// clone stored ones so we always have them available...then filter
var $opts = $subCatOpts.clone().filter(function() {
return !this.value || catId === $(this).attr('data-catid')
});
$('#subcategory').html($opts)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Category:
<select name="category" id="catagoryid">
<option value=""> -- Select Category -- </option>
<option value="1">Electronics</option>
<option value="2">Venues</option>
</select>
Subcategory
<select name="subcategory" id="subcategory">
<option value=""> -- Select Sub category -- </option>
<option value="1" data-catid="1">Electronics - Sub 1</option>
<option value="2" data-catid="1">Electronics - Sub 2</option>
<option value="3" data-catid="2">Venues - Sub 1</option>
<option value="4" data-catid="2">Venues - Sub 2</option>
</select>
Pass all the data on page load to browser.
<?php
$subcategories_json = array();
$subcategories = selectAllData('subcategories');
while ($row = mysqli_fetch_assoc($subcategories)) {
$subcategories_json[] = array(
'cat_id' => $row['cat_id'],
'sub_cat_id' => $row['sub_cat_id'],
'sub_title' => $row['sub_cat_title']
);
}
echo "<script>subcategories = ".json_encode($subcategories_json).";
</script>";
?>
Then in Javascript (something similar to this):
$(...).change(function(event) {
var subcategory_title = $(this).find('option:selected').attr("title");
for(k in subcategories)
{
if (subcategory_title==subcategories[k].id) {
$(this).append('<option>'+subcategories[k].name+'</option>')
}
}
});
You can solve this one using ajax, Call ajax - on change event of category select box. See Below link that describe dynamic category implementation:
jQuery ajax unlimited dynamic selectbox based on parent categories
What i have now:
1)31june.html
2)32june.php
I have a table "jewelry" with this structure:
id
brand(varchar)
type(varchar)
model(varchar)
collection(varchar)
description(text)
code(varchar)
url(varchar)
available(int)
First file 31june.html is a select box in which are listed types (earrings,necklace,watches), according to which type we choose the script will send the selected type to second file 32june.php.
32june.php will do another things:
1)query :
$sql='SELECT collection FROM jewelry WHERE type = ?'
2) echo another select box with query($sql) in it.
For example i have chosen in select box earrings, in DB jewelry table will be selected all collection with type earrings and this collection will be displayed in a new select box as an option.
What i want: i need to choose the type then the select box with collection will display according to type then I want to choose the collection in the generated select box and according to it, replace it (this collection name) with another select option or for example with the new result i want to display in this select box.
For example:
Type: earrings -> generated select box with collection option value coll1
I select coll1.
I want coll1 to be replaced with the new date.
<script type="text/javascript">
$(document).ready(function(){
$('#type').on("change",function () {
var chosen= $(this).find('option:selected').val();
$.ajax({
url: "31june.php",
type: "POST",
data: "chosen="+chosen,
success: function (response) {
console.log(response);
$("#ajdiv2").html(response);
},
});
});
});
</script>
<div id="ajdiv">
<select name="type" id="type">
<option>Select Type</option>
<option value="earrings">Earrings</option>
<option value="necklace">Necklace</option>
<option value="watches">Watches</option>
</select>
</div>
<div id="ajdiv2"></div>
<?php
$chosen = $_POST['chosen'];
function mm ($chosen){
$host="xxxx";
$pass="xxxx";
$user="xxxx";
$db="xxxx";
$connect ="mysql:host=$host;dbname=$db";
$pdo = new PDO($connect, $user, $pass);
$sql1='SELECT collection FROM jewelry WHERE type = ?';
$stmt = $pdo->prepare($sql1);
$stmt->execute(array($chosen));
foreach($stmt as $val){
$select = '
<select name="users" id="yol" onchange="showUser(this.value)">
<option value="">Select Collection:</option>
<option value="collection">
' . $val['collection'] . '</option>
</select>';
echo $select;
}
}
echo mm($chosen);
It might be an issue with your loop, you are creating multiple select elements. Try changing to :
$select = '
<select name="users" id="yol" onchange="showUser(this.value)">
<option value="">Select Collection:</option>
';
foreach($stmt as $val){
$select = $select . '
<option value="collection">
' . $val['collection'] . '</option>';
}
$select = $select . '</select>';
echo $select;
Then you can implement showUser(), or create another change handler for it instead like you have for type.
Good day community,
I have an ASP.NET MVC4 project, where on edit page I'm use jquery script. But I have a problem to display elements on the page.
Here is my dropdown's HTML markup before changes:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option value="3">testtsi</option>
<option selected="selected" value="4">testrtu3</option>
</select>
And here is after jquery changes
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
But it's display on the page not a selected element testrtu3, always display first element. And when I click save button saved my first value.
Here is my jQuery function:
$(document).ready(function () {
var values = [];
$(".checkboxUniversities:checked").each(function () {
values.push($(this).val());
});
$.getJSON('/Administrator/ProgramList/' + values, function (data) {
alert('Return json result new information');
var items = '<option disabled>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#ProgramId').html(items);
});
//var selectedElement = $("#ProgramId").find(":selected").text();
});
I guess I need somehow add selected value when create my dropdown inside jquery, or after creating, but I don't know how. Can anybody help me?
Before appeding options to your dropdown you have to save selected index or text in variable and use it further.
Sample Code:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
<input id="click" type="button" value="click me"/>
$(document).ready(function(){
var option = '<option value="1">testrtu1</option><option value="2">testrtu2</option><option value="3">testtsi</option><option value="4">testrtu3</option>';
$("input#click").click(function(){
var selInx = $("select[name='ProgramId'] option:selected").index();
$('#ProgramId').html(option);
$('select#ProgramId').prop('selectedIndex', selInx);
});
});
DEMO FIDDLE
NOTE: As we cannot connect to your backend code to get options hardcoded in code itself and on click of button dropdown will be replaced with latest options and will update the selected index based on first one. You can use either selectedindex or text based on your requirement.