Manipulate Json array on select change - javascript

I am new to JQuery and I am wondering if his is possible.
I have a PHP controller that sends a json encoded array to a view,
this is the json array:
{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}
Now on the view I have a the following:
<select id="selector">
<option value="">Select one</option>
<option value="1">blue</option>
<option value="8">green</option>
<option value="14">red</option>
</select>
<div id="description">
</div>
What I want to do is first populate the select list from the json array, then if I select green from the dropdown list the description for green should appear on the div, if I change my selection the appropriate description should appear on the div.
And the option I select should no longer appear on the select list like if I choose green, only red and blue should appear on the available option, if the I select another color let say blue then red and green should be available for another select.
I am currently doing it running a new query onchange of the select but I want to do it without another query and page refresh, I imagine it is possible since I already send the JSON array to the browser.
Hope I am clear on my problem and thank you for your help!

var data = [{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}];
var selector = $('#selector');
data.forEach(function(obj){
// create option
var option = $('<option>');
// set its value
option.val(obj.id);
// set its text
option.text(obj.text);
// append it to select element
selector.append(option);
}
selector.change(function(){
var value = this.value;
// show all options
selector.find('option').show();
// hide the selected
$(value).hide();
// find the selected object
var selected = data.filter(function(obj){
return obj.id == value;
});
// if returns exactly one show its description
if (selected.length == 1)
$('#description').text(selected[0].description);
});

Firstly you Jsonmust be like this :
[{"id":"1","color":"blue","description":"This is the color blue"},
{"id":"8","color":"green","description":"This is the color green"},
{"id":"14","color":"red","description":"This is the color red"}]
this is some code i have tried i think it will be help you :
$(document).ready(function(e){
$("#selector").on('change',function(){
var dataL= $("#selector option:selected").val();
$.post("Page_json.php",{myVal:dataL},function(data,message,xhr){
if(message==='success'){
$.each(data, function(k,v){
if(v.id == dataL){
$("#description").text(v.description);
return false;
}
});
}
},'json');
});
});

Related

Is there a way to show the selected option value in the select menu after turbolinks.visit(url)

I have select menu with bunch of options having "url's" as their value. Once user click on the option , it will take them to particular url. I want the selected option to be shown on select menu when taken to the particular url.
Code:
Html:
<div data-controller="dropdown">
<select id="abcMenu" data-action="dropdown#abc">
<option value="/abc">A</option>
<option value="/xyz">B</option>
<option value="/def">C</option>
</select>
</div>
Javscript
abc(){
var elt = document.getElementById('abcMenu');
elt.options[elt.selectedIndex].setAttribute('selected','selected');
var option = elt.options[elt.selectedIndex].value;
Turbolinks.visit(option);
}
Turbolinks will take to next path whereas dropdown option gets preselected to first option. Can anyone please let me know how to fix this.
You can use window.location.pathname to get the path and then set the corresponding option from the select:
function selectOptionByValue(element, value){
for(var i=0; i < element.options.length; i++) {
if(element.options[i].value == value) {
element.selectedIndex = i;
}
}
}
Where element is the select element and value is the path that you want to check.

select drop down option based on associated text

I have a drop down with a value and associated text as such:
echo '<option value="'.$row['company_id'].'">'.$row['company_name'].'</option>';
Eventually, the output of the selected option is put into a table, row by row. By each row, there is an edit button to edit that particular row and select a new drop down option. I'm trying to use JavaScript to select the text and when they hit the edit button, the option that is currently set will be the default choice.
So for instance, if the row says the company_name is: ABC Company, when they hit the edit button, the drop down will populate with that option. Since the value and text are different, I need to choose the drop down option based on text. I have tried these 2 options so far with no luck.
To get the row text:
var d = document.getElementById("itable").rows[id].cells[3].innerText;
I have tried the following to pass back the text of the row, and to select the drop down by text.
document.querySelector('#editinsurancepolicymodal select[name=editicompanydropdown]').value = d;
This option just populates the drop down, but no choice is selected.
document.querySelector('#editinsurancepolicymodal').find('option[text="InsuranceB"]').val;
This option selects the first option in the drop down, but doesn't change based on what the 'text' is.
Thank you for your help in advance.
One way will be to iterate over the option elements, selecting the one that has the same text as the text from the row, and un-selecting all the others. This is illustrated in the snippet below (I have inserted a 3 second timeout, so that you can see that the initially selected option (Two) is changed to the option with the text "Three" from the JavaScript code.
window.setTimeout(function () {
var sampleWord = "Three";
var options = document.querySelectorAll("option");
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === sampleWord) {
option.selected = true;
} else {
option.selected = false;
}
}
}, 3000);
<select id="selector">
<option id="option-1" value="1">One</option>
<option id="option-2" value="2" selected>Two</option>
<option id="option-3" value="3">Three</option>
<option id="option-4" value="4">Four</option>
</select>
Alternately, you could store the id for the company as a data-attr attribute on the row. For example (in PHP):
echo "<td data-attr-company-id=".$row['company_id'].">".$row['company_name']."</td>"
Then, you can read the attribute from the table row, and query for the option that has the same value as your attribute value.
var options = document.querySelectorAll("option");
This will select all options from the page. If you want to get the options for a specific drop down, use the following:
var options = document.querySelector('#specificform select[name=specific_drop_down_in_the_specific_form]');
To select the option based on the text and not the value, use this loop:
for (var i=0; i<options.length; i++){
var option = options[i];
if (option.innerText === d){
option.selected = true;
}
}

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);
}

Make dropdown multi-select

I have 2 dropdowns and one of them(the second one) is dynamic in the sense that its values change according to the option chosen in the first dropdown.
JSFiddle result: http://jsfiddle.net/pgbw56vb/10/embedded/result/
Can someone pls show me how i can make the second dropdown a multi-select? I'm really green in Jquery and html.
JSFiddle: http://jsfiddle.net/pgbw56vb/10/
<select id="kategorie_oder_seite"></select>
<select id="auswahl"></select>
var data = {
"Kategorie": ["Kraft", "Startseite", "Insurance", "Risk",],
"Seite": ["http://jsfiddle.net/tony089/pgbw56vb/2/", "https://stackoverflow.com/users/login?returnurl=%2fquestions%2fask"],
};
var $kategorien = $("#kategorie_oder_seite").on("change", function() {
var seiten = $.map(data[this.value], function(seite) {
return $("<option />").text(seite);
});
$("#auswahl").empty().append(seiten);
});
for (var kategorie in data) {
$("<option />").text(kategorie).appendTo($kategorien);
}
$kategorien.change();
Thanks in advance.
you can use the multiple attribute of select tag and set its value to multiple. also remember to set the name property in array form so that you could send multiple values via this select control.
eg.
<select multiple="multiple" id="kategorie_oder_seite" name="check[]"></select>
JsFiddle: http://jsfiddle.net/pgbw56vb/10/
just add "multiple" attribute on the "select" tag
Add multiple to your select tags.
<select id="kategorie_oder_seite" multiple></select>
<select id="auswahl" multiple></select>

Jquery remove select options based on text input

I'm trying to do the following:
I have an input <input type="text" value="red,yellow,blue" id="colors" />
and a dropdown list
<select name="colors_dropdown" id="colors_dropdown">
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
</select>
I want to remove the select options that are in the text input. For example if text input value=red,blue the dropdown should have just option yellow.
I was able to make arrays of the comma separated values in the text input and values in dropdown options.
var selected_colors = $('#colors').val().split(","); //array of colors from text input
var all_colors = $.map($("#colors_dropdown")[0].options, function(option)
{
return option.value; //array of all colors from dropdown
});
Based on that, I'm looking for a way to populate the dropdown list with all colors except those in the selected_colors arrays.
var selected_colors = $('#colors').val().split(","); //array of colors from text input
jQuery.each(selected_colors, function() {
$("#colors_dropdown option:[value='" + this + "']").remove();
//Or use text attribute:
//$("#colors_dropdown option:[text='" + this + "']").remove();
});
Working Demo: http://jsfiddle.net/83Vg9/2/
This will remove the exact matching colors. Using contains could be remove all matching options for e.g. if the text box contains only e it will remove yellow, blue, red, green everything...
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate each color
$.each(selected_colors, function(index, color) {
// iterate over each option & remove if necessary
$('#colors_dropdown option').each(function(){
if (this.value == color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
}
})
});
EDIT
Just realized that you don't need to use two each() as shown above. Try this -
// make an array
var selected_colors = $('#colors').val().split(",");
// iterate over each color and remove it from the dropdown
$.each(selected_colors, function(index, color) {
$("#colors_dropdown option:[value='" + color + "']").remove();
});

Categories