my multi-select selection is only giving the output as my first selection. I'm sending the data to firebase, and only the first selection is reflected there. For example, if I select (energy, health care, real estate) in my firebase it only shows energy.
Here is my HTML code:
<select name="Sector" value="sector" id="interested_sector" class="selectpicker" multiple="multiple" data-live-search="true">
<option value="">Sector</option>
<option value="energy">Energy</option>
<option value="materials">Materials</option>
<option value="consumer discretionary">Consumer Discretionary</option>
<option value="consumer staples">Consumer staples</option>
<option value="health care">Health Care</option>
<option value="financials">Financials</option>
<option value="information technology">Information Technology</option>
<option value="telecommunication services">Telecommunication services</option>
<option value="utilites">Utilites</option>
<option value="real estate">Real Estate</option>
</select>
Here's is the snippet of code in my .js file that sends data to realtime database
var interested_sector = getInputVal('interested_sector')
function getInputVal(id){
return document.getElementById(id).value;
}
function saveUserInfo( interested_sector){
firebase.database().ref('User_info/'+id).update({
interested_sector: interested_sector,
}).then(() => {
window.location = //it goes to a different html page;
})
}
A firebase RealTime Database is made up of JSON Objects, when you get the Values from the input, make sure they return in proper format, here, you seem to be updating an existing key that is called interested_sector and adding value health, energy etc to it. As Realtime Database accepts JSON, what you send has to be a proper JSON, that is where your code is breaking the value and probably taking the first number, you need to run through all the values taken in and decide in what format do you want to store them?
for example:
{
interested_sector: {
1: 'health',
2: 'energy'
}
}
or
{
interested_sector: "health, energy"
}
as you can see both are working options, but you need to parse the values first before you send them for an update.
So after testing your code, it turns out that interested_sector value changes everything you select a new value, it replaces the old value, that is why when you update the field in firebase database, it only shows the latest of the values,
so for example:
if you select 'Energy' and hit the button to save info, it will save 'Energy'
and then you click on 'Materials' and hit the button to save the info, the interested_sector value gets changed and replaces the old value and the function to save the info changes the firebase value as well.
solution is to add a local var that keeps the value and keeps on appending them interested_sector += new value and use a separator like ',' or ';'.
so the correct code of the above, should be something like this:
<!DOCTYPE html>
<html>
<body>
<select name="Sector" value="sector" id="interested_sector" class="selectpicker" multiple="multiple" data-live-search="true">
<option value="sector">Sector</option>
<option value="energy">Energy</option>
<option value="materials">Materials</option>
<option value="consumer discretionary">Consumer Discretionary</option>
<option value="consumer staples">Consumer staples</option>
<option value="health care">Health Care</option>
<option value="financials">Financials</option>
<option value="information technology">Information Technology</option>
<option value="telecommunication services">Telecommunication services</option>
<option value="utilites">Utilites</option>
<option value="real estate">Real Estate</option>
</select>
<button onclick="getCalled()">Get Called</button>
<script>
var final_val = "";
function getInputVal(id) {
return document.getElementById(id).value;
}
function getCalled() {
var interested_sector = getInputVal('interested_sector');
final_val += interested_sector + ', ';
console.log(final_val);
alert(final_val);
}
</script>
</body>
</html>
FYI: firebase's update function doesn't append to the old value, it changes only the specific fields that you want to change and keeps all the other fields the same. unlike ref().set() function which completely rewrites the entire json object
Related
I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});
So I am making two dropdowns. One is dependent on the other one, as in when you choose an option in the first dropdown, the values in the other should change. I am rendering my form with Symfony3.4, so I do not have much control over it. (I do not think I can add dynamic class names/value names to it). If it is relevant, I am using Bulma css framework.
Here is what my selectboxes look like:
states:
<select name="state" id="stateSelect">
<option value="1">Lagos</option>
<option value="2">Abuja</option>
<option value="3">Rivers</option>
<option value="4">Ogun</option>
<option value="5">Oyo</option>
<option value="6">Anambra</option>
<option value="7">Enugu</option>
<option value="8">Akwa Ibom</option>
<option value="9">Adamawa</option>
...
<option value="37">Zamfara</option>
</select>
LGA (local government areas):
<select id="lgaSelect" name="areas_registration[lga]">
<optgroup label="Lagos">
<option value="1">Abule Egba</option>
<option value="2">Agege</option>
<option value="3">Ajah</option>
<option value="4">Alimosho</option>
<option value="5">Amuwo Odofin</option>
...
</optgroup>
<optgroup label="Abuja">
<option value="38">Apo</option>
<option value="39">Asokoro</option>
<option value="40">Central Area</option>
<option value="41">Chika</option>
<option value="42">Dakibiyu</option>
...
</optgroup>
....35 more optgroups
</select>
My goal is when a user chooses an option from States dropdown, the LGA dropdown should only have options relevant to the selected state. I am using optgroup label for this. What I tried in my javascript is that when the page loads, I clone the LGA dropdown, hide it, call it lgaSelectSeed and use it for seeding the original LGA dropdown: (#hiddenLgas is just an empty div)
$(function () {
var stateSelect = $("#stateSelect") || null;
var lgaSelect = $("#lgaSelect") || null;
var hiddenLga = $("#hiddenLgas") || null;
$(hiddenLga).html(lgaSelect.clone().prop('id', 'lgaSelectSeed'));
stateSelect.change(function () {
var select_class = $(this).find('option:selected').text();
var options = $(lgaSelectSeed).find('optgroup[label="' + select_class + '"]');
$(lgaSelect).html(options.children());
}
This works but there is a bug in it. If you select random options in the state dropdown, and then go up and select Lagos or Abuja, the LGA dropdown becomes blank. I have been trying to figure out for a few days why this is happening, but still cant. Is there any jquery plugin to handle this instead?
DEMO: https://jsfiddle.net/gafyvbL9/
How to replicate the bug: In the states dropdown (left), choose Lagos. Then choose Anambra. Then choose Lagos again, then choose Anambra. You can see that the LGA dropdown (right) becomes empty. Why is this happening? Thanks in advance
Make a clone of the stored options so you don't remove the originals from $(hiddenLga)
Change:
$(lgaSelect).html(options.children());
To
$(lgaSelect).html(options.children().clone());
Playing with your fiddle, I think the issue is when you perform $(lgaSelect).html(), you're deleting all of the information stored there. Try storing that outside of your handler.
let $options = $('#lgaSelect').clone();
$("#stateSelect").on('change',function() {
let state = $(this).find('option:selected').text();
$("#lgaSelect").html($options.find(`optgroup[label="${state}"]`).html());
});
EDIT:
Notice the double quote in optgroup[label="${state}"]. This prevents issue with states that contain a space, like Akwa Ibom.
I want to achieve:
If I select "16" in first select box and bigger value in second, for example "17", then in second select automatically changing to "16".
Just if value in first select box is lower than second, always change to same values, for example 16 to 16, 18 to 18.
<select id="from_age_js" name="from_age" class="select-advertise-style">
<option value="f13">13</option>
<option value="f14">14</option>
<option value="f15">15</option>
<option value="f16">16</option>
<option value="f17">17</option>
<option value="f18" selected>18</option>
<option value="f19">19</option>
<option value="f20">20</option>
</select>
—
<select id="to_age_js" name="to_age" class="select-advertise-style">
<option value="t13">13</option>
<option value="t14">14</option>
<option value="t15">15</option>
<option value="t16">16</option>
<option value="t17">17</option>
<option value="t18">18</option>
<option value="t20" selected>20+</option>
</select>
That's an easy one, in your case, with pure javascript, I would do something like this:
function checkit()
{
//Store the two dropdowns for easy reference
var fromAge = document.getElementById('from_age_js');
var toAge = document.getElementById('to_age_js');
//Verify if the toAge value is minor, to see if the conditional code will be executed
if( fromAge.options[fromAge.selectedIndex].value >
toAge.options[toAge.selectedIndex].value)
{
//In that case, match the values to be the same...
document.getElementById('to_age_js').value =
fromAge.options[fromAge.selectedIndex].value;
}
}
And you just have to add that function to where you want it to be called. I would choose to add the onchange event from Javascript within the select dropdowns. Like this:
<select id="from_age_js" name="from_age" class="select-advertise-style" onchange="checkit();">
You can see a working example here:
https://jsfiddle.net/8cmad3tz/19/
I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
For paging I have this code which enables me to update the querystring without losing any elements in the querystring.
var tRVD = new RouteValueDictionary(ViewContext.RouteData.Values);
foreach (string key in Request.QueryString.Keys)
{
tRVD[key] = Request.QueryString[key];
}
tRVD["page"] = #i;
#Html.ActionLink(#i.ToString(CultureInfo.InvariantCulture), "Index", tRVD);
I need to do the same with sorting. I have the following code but of course the querystring is overwritten by sortby. What I need is the same as I have for paging, something that just adds sortby to the querstring if it is not there and updates it if it is. How is this possible?
<form name="sortbyformtop">
<select onchange="location.href=this.options[this.selectedIndex].value" name="sortbyselecttop">
<option value=""></option>
<option value="sortby=accommodationtype">Accommodation type</option>
<option value="sortby=mostreviewed">Most reviewed</option>
<option value="sortby=lowestprice">Lowest price</option>
</select>
</form>
So, what I'm trying to achieve is setting the querystring to the same value as it is now plus sortby.
You need to add an <input type="hidden"> to your form for each value in the querystring.