Updating Textbox's info upon selecting listbox item using javascript - javascript

I'm trying to update Textbox's with the selected items info(properties). Can I get the selected Items Name instead of the Id, or in other words how can I get the properties of whats in my ViewData in the javascript upon selecting an item and then set it to a txtbox?
#Html.ListBox("ListBoxName", new SelectList((IEnumerable<Epic>)ViewData["selectedestimate"], "Id", "Name", "EstimatedTime"), new {#class = "ListBoxClass", #style = "height: 325px;"})
#Html.TextBoxFor(model => model.Name, new {#class = "TimeClass"})
<script type="text/javascript">
$(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
// get items properties and info so that the value can be set to a textbox
//set textbox value to Name of selected Value
$(".TimeClass").val(selectedid);
event.preventDefault(); // Stop the browser from redirecting as it normally would
$.get('#Url.Action("UserStoriesList", "Estimate")', { id: selectedid }, function (result) {
$('#stories').html(result);
});
});
});
</script>

A ListBox is like a DropDownList except that it allows for multiple items to be selected. It uses the same HTML tag (<select>) but it adds the multiple attribute. So when rendered your markup will look like this:
<select id="ListBoxName" name="ListBoxName" multiple="multiple">
<option value="id1">text 1</option>
<option value="id2">text 2</option>
<option value="id3">text 3</option>
...
</select>
So as you can see you have information about the id and the text inside the DOM. If you wanted to fetch some other information about the selected item you will need to send an AJAX request to the server and pass the selected id to retrieve it. So if you only wanted to show the text:
$(function() {
​$('.ListBoxClass option')​.click(function() {
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
$('.TimeClass').val(selectedText);
...
}
});​
});
The click handler will run everytime the user clicks on an element in the listbox but the if condition will be satisfied only if he selected the item.

Related

I want to send the option selected from dropdown to local storage and get it to display on another page, but its showing null

This is the dropdown in the 1st html page where 1 option is selected.
<body>
<label for="select">Gender:</label>
<select name="select" id="select">
<option value = "0">Select</option>
<option value = "1">Male</option>
<option value = "2">Female</option>
<option value = "3">Other</option>
</select>
</body>
This is the script i'm using to store selected option in the local storage.
<script>
var options = [];
$("#select option").filter(":selected").each(function(index) {
var option = $(this).text();
options.push(option);
$("#select").text(options.toString())
});
localStorage.setItem('select', options);
</script>
This is another page where i want to display the selected option.
<body>
<p> Gender: <span id="display_select"></span></p>
</body>
This is the script to get the selected option from the local storage and display it on the 2nd page.Its showing null.
$(document).ready(function() {
for (let i = 0; i < localStorage.length; i++) {
var options = localStorage.getItem("select");
$("#display_select").text(options);
}
});
The script you have for storing the select value doesn't actually do what you think it does. What you need to do is have an event handler that runs when the select value changes and stores the value in localStorage at that point. What you have simply runs once when the page is first loading.
$("#select").on("change", function() {
localStorage.setItem('select', this.textContent);
});
Then to get the value later...
$(document).ready(function() {
$("#display_select").text(localStorage.getItem("select"));
});
Problem is in your first script file where You store value,
var options = [];
$(document).ready(function(){
$('#select').change(function(){
//console.log($(this).val());
localStorage.setItem('select', $(this).val());
});
});
localStorage only supports strings. For this to work you have to use JSON.stringify() and JSON.parse().
localStorage.setItem('select', JSON.stringify(options));
//...
var storedSelect = JSON.parse(localStorage.getItem('select'));
Your exemple to get a option selected:
$('#select').change(function() {
localStorage.setItem('select', $('#select option:selected').text());
});
var select = localStorage.getItem('select');
$("#display_select").html(select);

Dynamically filled HTML select, change selected visual . Blade Laravel template

I have this code. I'm working in Blade template by Laravel framework.
<select class="form-control" name="id_zupanije" id="id_zupanije" onchange="popuniGradove(this, document.getElementById('id_grada'))">
#foreach($zupanije as $zupanija)
#if($zupanija->id == $idzupanije)
<option value="{{$zupanija->id}}" selected="selected">{{$zupanija->naziv_zupanije}}</option>
#else
<option value="{{$zupanija->id}}" selected="">{{$zupanija->naziv_zupanije}}</option>
#endif
#endforeach
<option value="0" selected="">--Odaberite--</option>
idzupanije is id of the select option that needs to be selected...
javascript function "popuniGradove" is for creating select options for another select.
What I want to know is how to visual update selected option, so when window loads I see created select and showing me selected option, not this one
"--Odaberite--".
EDIT
here is screenshoot of how it looks..
I have 3 selects.. first is Zupanija (eng. "province"), Grad (eng. City), Kvart (eng. quart).. when I select zupanija, select grad is filled with options -> cities that have foregin key id_zupanija in table .. samo for kvart, after city is selected, javascript creates options with proper kvarts
... After I press submit (bnt Filtriraj) I refresh the page and filter results below... but I want my selects to save their choosen options before before submiting.. they keep showing --Odaberite-- (default option, last created) afer submiting..
If I understand you right you could consider using a Package like the old laravel 4 FormBuilder.
E. g. https://github.com/kristijanhusak/laravel-form-builder
That way you can bind every form to the respective model like so:
{!! Form::model($user, array('route' => array('user.update', $user->id))) !!}
Laravel automatically checks if input is existing in cache and will attach that data to the form.
You have to add 2 selectize, in this example we have first one for states (for example) and a second one for cities (for example). when we select a state the page send an ajax request to fetch cities in this state, then we set cities list on the cities' select.
the state select :
<select id="select-cities-state" class="selectized">
<option value="1">State 1</option>
...
</select>
the cities select :
<select id="select-cities-city" class="selectized" disabled="">
<option value=""></option>
</select>
var xhr;
var select_state, $select_state;
var select_city, $select_city;
$select_state = $('#select-cities-state').selectize({
onChange: function(value) {
if (!value.length) return;
select_city.disable();
select_city.clearOptions();
select_city.load(function(callback) {
xhr && xhr.abort();
xhr = $.ajax({
url: 'https://jsonp.afeld.me/?url=http://api.sba.gov/geodata/primary_city_links_for_state_of/' + value + '.json',
success: function(results) {
select_city.enable();
callback(results);
},
error: function() {
callback();
}
})
});
}
});
$select_city = $('#select-cities-city').selectize({
valueField: 'name',
labelField: 'name',
searchField: ['name']
});
select_city = $select_city[0].selectize;
select_state = $select_state[0].selectize;
select_city.disable();

Make select box change values when another value is selected from another select box

I want my select box to change depending which option I choose in the first select, and I want to hide the values that are not from that option/
My HTML here:
<select id="localidad">
#foreach (ja_era.Models.Localidades localidad in ViewBag.localidades)
{
<option value="#localidad.Id">#localidad.Zona</option>
}
</select>
<select name="Localidad" id="barrio">
#foreach (ja_era.Models.Barrios barrio in ViewBag.barrios)
{
<option class="#barrio.Localidad" value="#barrio.Id">#barrio.Barrio</option>
}
</select>
The Localidad select has 4 options and bring the countries, then I have the second select that brings the cities all in one select box. Which ones are well defined in my database.
You can see here that "Barrios" has the column localidad where I insert the localidad id
I have tried some js code but can't figure it out how to make it work.
$(document).ready(function() {
$('#localidad').change(function () {
});
})
Basically you need to get the value of the selected option of the first dropdown, send it to your an action method and let it return the data for the second dropdown in json format. Then you will go through the items in the JSON array and build the markup for the options in the second dropdown.
$(document).ready(function() {
$('#localidad').change(function () {
var v = $(this).val();
var urlToGetData="#Url.Action("GetBarrios","Home")";
var items="";
$.getJSON(urlToGetData+"?id="+v,function(a,item){
items+="<option value='"+item.Value+"'>"+item.Text+"</option>";
})
$("#barrio").html(items);
});
})
Assuming you have GetBarrios action method like this
public ActionResult GetBarrios(int id)
{
var items=db.Barrios.Where(s=>s.Localidad==id)
.Select(s=> new SelectListItem {
Value=s.Id.ToString(),
Text = s.Barrio
}).ToList();
return Json(items,JsonRequestBehaviour.AllowGet);
}

Auto select new added value with ng-options and AngularJS

I have a select list looking like this:
<select
class="form-control"
ng-model="locationList"
ng-options="location.place group by location.type for location in locationlist | orderBy:['type']"
ng-change="addMissingLocation(locationList)">
<option value="">From</option>
</select>
The last item of the ng-options list is called "Add location", and triggers the following function through ng-change:
$scope.addMissingLocation = function (locationList) {
if (locationList.place == "Add location") {
$('.addMissingLocation').modal('show');
}
}
A modal shows, and it allows the user to add a new location using the following function:
$scope.addLocationOtherExtra = function () {
$scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
jsonToLocationLocalStorage($scope.locationlist);
$scope.formLocationOther = '';
$('.addMissingLocation').modal('hide');
};
What I am trying to accomplish, is that once the user introduces a new location and the modal closes, the selected value in the select, is this newly added value.
I'm not even sure if such thing is possible.
Any tips?
After adding new option you should point ngModel to added option. Try this to select the last option (new one):
$scope.addLocationOtherExtra = function () {
$scope.locationlist.push({ place: $scope.formLocationOther, type: "-Secondary Locations", main:false});
$scope.locationList = $scope.locationlist[$scope.locationlist.length - 1];
jsonToLocationLocalStorage($scope.locationlist);
$scope.formLocationOther = '';
$('.addMissingLocation').modal('hide');
};

Access selected values from html multiselect with javascript

This is my multiselect form HTML
<select id="designation" name="designation" multiple="multiple">
<option value="cheese" >Cheese</option>
<option value="tomatoes" >Tomatoes</option>
<option value="mozarella" >Mozzarella</option>
</select>
Here is how I'm trying to access the selected values with js.
$(document).ready(function(){
$('#designation').multiselect();
var selectedValues = $('#designation').val();
});
selectedValue is always assigned nul by $('#designation').val()
How can I fix this ?
I have also tried
$("select.designation option:selected").val();
You multiselect will initially be null when the page loads, which is what your code is showing. The code below will update the variable selectedValues whenever you click away the multiselect box.
$(document).ready(
function(){
$('#designation').click(function() {
var selectedValues = $('#designation').val();
});
}
);
Example here: http://jsfiddle.net/83brpjav/
.multiselect("getChecked") method returns all selected check boxes
Try this -
For single selection-
var value = $('#designation').multiselect("getChecked").val();
console.log(value);
For multiple selection -
var values = $('#designation').multiselect("getChecked").map(function(){
return this.value;
}).get();//return you the all selected values as an array
console.log(values);

Categories