I have 2 select lists and I would like to populate the options in the 2nd list based on the selection of the first list.
This is the first list:
<select class="" id="applicationForm_package">
<option value="no_package">Please select a package</option>
<option package_identifier="package_5" value="5">Package 1</option>
<option package_identifier="package_60" value="60">Package 2</option>
<option package_identifier="package_58" value="58">Package 3</option>
<option package_identifier="package_55" value="55">Package 4</option>
</select>
I then have (in javascript) and variable for each package in the first list:
<script>
var package_5 = "<option value='20'>1 Month</option><option value='110'>6 Months</option><option value='200'>12 Months</option>";
var package_60 = "<option value='25'>1 Month</option><option value='140'>6 Months</option><option value='250'>12 Months</option>";
var package_58 = "<option value='26'>1 Month</option><option value='146'>6 Months</option><option value='270'>12 Months</option>";
var package_55 = "<option value='37'>1 Month</option><option value='212'>6 Months</option><option value='400'>12 Months</option>";
</script>
As the user interacts with the first select list, I would like the options from the respective variables to populate the 2nd list.
Below is the 2nd select and the javascript that I have written. Everything seems to work fine, the issue is the 2nd select list is not getting updated. In my else statement, the console is working but the variable is not defined when I check it in my console.
<select id="applicationForm_subscription">
<option value="no_package_selected">Please select a package First</option>
</select>
<script>
var noPackageSelected = "<option value='no_package_selected'>Please select a package</option>";
jQuery( "select#applicationForm_package" ).change(function() {
var package_name = jQuery( "select#applicationForm_package option:selected").text();
var package_id = jQuery( "select#applicationForm_package option:selected").val();
if(package_id == "no_package"){
jQuery("select#applicationForm_subscription").find("option").remove().end().append(noPackageSelected).val("no_package_selected");
}else{
console.log("update subscriptions");
var get_selected_package_name = jQuery("select#applicationForm_package option:selected").attr('package_identifier');
jQuery("select#applicationForm_subscription").find("option").remove().end().append(get_selected_package_name);
}
});
Any assistance would be great.
Cheers,
Your code is messy for such a simple task as conditionally changing the innerHTML of an element.
A few things to note:
$ is a short-hand for jQuery
you can use $('select').val() to get the value of the selected option
it is redundant to use tag#id for identification, #id is both faster and shorter
If I understand you right, you want to:
listen to the change event of a (first) select,
see if its value is appropriate,
populate a second list based on selection from the first.
I recommend using an Object to store the markup for the second list - so that it would be more straightforward to only store a package ID in each option of the first list:
HTML
<select class="" id="applicationForm_package">
<option value="5">Package 1</option>
<option value="60">Package 2</option>
<!-- ... -->
</select>
... and then set the second list's innerHTML using that ID with a string from the packages object:
JavaScript
var packages = {
5: "<option value='20'>1 Month</option><option value='110'>6 Months</option><option value='200'>12 Months</option>",
60: "<option value='25'>1 Month</option><option value='140'>12 Months</option><option value='250'>24 Months</option>",
58: "<option value='26'>1 Month</option><option value='146'>2 Months</option><option value='270'>4 Months</option>",
55: "<option value='37'>1 Month</option><option value='212'>4 Months</option><option value='400'>8 Months</option>"
};
$('#applicationForm_package').change(function () {
// see if there is listing for this package ID
if (packages.hasOwnProperty($(this).val()))
{
// List options
$('#applicationForm_subscription').html(packages[$(this).val()]);
}
else
{
// Please select a package First
$('#applicationForm_subscription').html('Please select a package First');
}
});
Working example on JSFiddle.
If you want dynamicaly get the content of the variable based on name then you should use this:
jQuery("select#applicationForm_subscription").find("option").remove().end()
.append(window[get_selected_package_name]);
Related
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
I have a jquery code which changes according to the previously selected value of drop-down.
I use it when I have two drop-downs and it works flawlessly.
Now the problem is that I am working with 3 drop-downs and I am unable to modify the code according to 3 drop-downs (reason my being new to jquery).
This is the code:
Jquery:
jQuery(function(){
var $cat = $('select[name=coursename]'),
$items = $('select[name=semno]');
$cat.change(function(){
var $this = $(this).find(':selected'),
rel = $this.attr('rel'),
$set = $items.find('option.' + rel);
if ($set.size() < 0) {
$items.hide();
return;
}
$items.show().find('option').hide();
$set.show().first().prop('selected', true);});});
I used two drop-downs namely, coursename and semno, with this code and it works perfectly fine.
Now I want to add another dropdown, subnm which comes after semno.
So what I exactly want is that when a person makes a particular selection in coursename the relevant items should appear in semno and among those relevant items, when a value is selected, the items are listed on subnm accordingly.
I have used rel and class in the option element.
HTML Code
Course:
<select name="coursename" id="coursename">
<option value="xyz" rel="xyz">XYZ</option>
<option value="abc" rel="abc">ABC</option>
</select>
Semester:
<select name="semno" id="sem">
<option value="one" class="xyz">I</option>
<option value="two" class="xyz">II</option>
<option value="three" class="abc">III</option>
</select>
Subject:
<select name="subnm" id="subnm">
<option value="p">p</option>
<option value="q">q</option>
<option value="r">r</option>
</select>
I guess I will need a rel option on the semno drop-down and then class on the subnm drop-down in accordance to the semno rel.
Forgive me if I am not 100% comprehensible. I am new to this site and I really need help.
Thank You in advance!
Hope this is what you want. I have used the same function for change event for the second select menu.
$items.change(function(){
var $this = $(this).find(':selected'),
rel = $this.attr('rel'),
$set = $third.find('option.' + rel);
if ($set.size() < 0) {
$third.hide();
return;
}
$third.show().find('option').hide();
$set.show().first().prop('selected', true);
});
Also I have triggered the change event for second select in change event handler of first select.
$items.trigger("change");
Please refer this fiddle
Currently I am working on a site where I do not have access to the perl generated options of a drop down list. The drop downs are populated dynamically and not all options are available to all users.
The code I am able to work with is shown here.
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;" ></select>
PRIMARY_POS
populates each option that is able to be selected.
The actual output as seen when the page renders is
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;">
<option value="0">None Selected
<option value="155935">Option4
<option value="155934">Option3
<option value="155905">Option2
<option value="155933">Option1
<option value="155932">Option5
</select>
What I need to be able to do is set a sort order based on a hidden attribute that is assigned based on the text value
So in the above example. I need the drop downs ( Important as their are mulitple drop downs on the page ) to be able to be sorted by a not yet created attribute
So that the above code might then be
<option value="0">None Selected
<option sortvalue="5" value="155935">Option4
<option sortvalue="4" value="155934">Option3
<option sortvalue="3" value="155905">Option2
<option sortvalue="2" value="155933">Option1
<option sortvalue="1" value="155932">Option5
</select>
The sortvalue being set base don the Text value of the option select. So that a sortvalue of 5 would be assign to Option4. Just a smaple as the text will need to be assigned.
End result should be that the Drop down list now has a custom attribute of Sortvalue and the select drop down is now sorted by that value.
Once again, I can not directly change the attributes but can manipulate the results. Hope that was easy to follow, which I doubt :/
You can create an object where the keys are the text and values are sort order. Then loop over options and add attribute based on that map
var optsMap = {
"Option4": 5,
"Option5": 1
......
};
var $select = $('select[name=PRIMARY_POS]')
$select.find('option').attr('data-sortvalue', function(){
return optsMap[$(this).text()] ||0;
}).sort(function(a,b){
return +($(a).data('sortvalue')||0) - +($(b).data('sortvalue')||0);
}).appendTo($select);
You can then read the value using:
$select.change(function(){
alert($(this).find(':selected').data('sortvalue'));
})
If all you are needing is sorting and don't need attribute can remove one step
DEMO
Common practice is to prefix those "added attributes" with data. You could try something like this with jQuery, if I'm understanding you correctly.
Example fiddle: https://jsfiddle.net/30cvudz8/7/
<select class="my-select">
<option data-sort-value="3" value="1">Option 1</option>
<option data-sort-value="5" value="2">Option 2</option>
<option data-sort-value="4" value="3">Option 3</option>
<option data-sort-value="1" value="4">Option 4</option>
<option data-sort-value="2" value="5">Option 5</option>
</select>
var optionList = new Array();
$('select.my-select option').each(function() {
optionList[optionList.length] = $(this).attr('data-sort-value')+'::'+$(this).val();
});
optionList.sort(); // sort it
var newOptionList = '';
for(var i = 0; i < optionList.length; i++) {
// recreate option
var parts = optionList[i].split('::');
newOptionList += '<option value="'+parts[1]+'" data-sort-value="'+parts[0]+'">Option '+parts[1]+'</option>';
}
// wipe and repopulate the select list
$('select.my-select').html(newOptionList);
To add an attribute (like data-sort-value) after you have a select list, you can do something like this:
$('select.original option').each(function() {
var sortingValue = getSortingValueFromText($(this).text());
$(this).attr('data-sort-value', sortingValue);
});
I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem
You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...
Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange
Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/
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.