How to add a value to the JavaScript variable? - javascript

var options = $('#mobility-table').find('select.MobilityCountry[data="'+selectionId+'"]').data('options').filter('[data="' + id + '"]');
options.sort(function(a,b) {
if (a.innerHTML > b.innerHTML) return 1;
else if (a.innerHTML < b.innerHTML) return -1;
else return 0;
The above code will give me all the list of cities upon selecting a country. I would like to add a default value 'All' at the first place in the variable 'options'. Can any one suggest me how to add this. Any help greatly appreciated. Thankyou.
Ex: options should have 'All,London,Scotland,Stanmore, Watford'.

You can use unshift() to add an element to the beginning of the sorted array:
If you're just trying to add text to the first element, it would be like this:
options.sort(function(a,b) {
if (a.innerHTML > b.innerHTML) return 1;
else if (a.innerHTML < b.innerHTML) return -1;
else return 0;
}
options.unshift("All");
If you want to add an option element to the array, it would be like this:
var item = document.createElement("option");
item.value = "all";
item.innerHTML = "All";
options.unshift(item);
It isn't clear to me whether you're also trying to change your HTML. If so, then please show what your HTML looks like so we can advise how to add that element to the DOM. It's not clear to me what HTML item is the select item.
In jQuery, you could add the option to be the first item in the drop-down like this
// you have to fill in the appropriate selector for your select object
$("#selector for select object").prepend("<option value='all'>All</option>");

unshift() a new <option>:
var option = document.createElement("option");
option.value = "all";
option.appendChild(document.createTextNode("All"));
options.unshift(option);
jQuery:
options.unshift($("<option>", {text: "All", value: "all"}).get(0));

Related

Change the selected option of HTML Select element: behavior is different when I use cursor

I have written a simple JS code that changes the selected option of an HTML Select element. Although the selected option changes to the desired value, the page doesn't respond to that. But when I use the cursor to change the selected options, the page truly responds. Do you have any idea what's the problem?
I think the problem is not due to my option toggling code, btw, it's the JS function I use:
function changeTheSelection() {
var selectElement = document.getElementById(selectInputId);
var opts = selectElement.options;
console.log("num of options found: " + opts.length);
for (var idx = 0; idx < opts.length; idx++) {
var opt = opts[idx];
if (!opt.selected) {
selectElement.selectedIndex = idx;
console.log("option " + idx + " selected.");
break;
}
}
}
Found the problem!
I have to add this:
selectElement.dispatchEvent(new Event('change'));
Sorry for this silly question...

Values from dynamicly generated select are 'undefined'

I have a table that dynamicly generates new rows and I need to get values from dynamicly generated selectbox. But all I get is 'undefined'. If I try to get values from dynamic <input> then everything works fine. Problem is just with selectbox.
Here is my code that gets values from user
$("#myTable tr").each(function(index, element){
if(index === 0){ // skip the table head
return true;
}
var option = $(element).find("#course option:selected");
if(option.val() == "-1"){ // should skip empty row but doesn't work either
return true;
}
$(element).children().each(function(index, element){
if(index === 0){
activities[activities.length] = $(element).find("input").val();
}else if(index === 1){
activityIds[activityIds.length] = option.val();
activityType[activityType.length] = option.attr("type");
}
});
});
JSFiddle http://jsfiddle.net/8rrmr/
Thanks for any help
In your addNewActivityRow function, you are not giving your select box the #course id. Actually, you should not use ids in this case but classes since an id must be unique for a page. Change the following line:
var option = $(element).find("#course option:selected");
to:
var option = $(element).find("select option:selected");
and it will work, but it would be best to remove all ids from your elements if you are going to have multiple instances of them
try something like this,FIDDLE
CHANGE THIS
// can't find #course
var option = $(element).find("#course option:selected");
TO
var option = $(element).find("select option:selected");
Try this,
activityIds[activityIds.length] = $(element).find('select').val();
activityType[activityType.length] = $(element).find('input').attr("type");

How do I add items to multiple drop down lists at the same time with Javascript in Razor?

I'm creating an MVC form, and I have multiple checkboxes and two drop down lists. I have figured out how to populate the first DDL based on what boxes are checked (i.e. empty at the beginning, checking boxes fills the items). However, I want to add another DDL that has the same items and populates in the same manner. My code looks like this:
<script type="text/javascript">
function checkedToggle(value, checked) {
x = document.getElementById("filter1");
y = document.getElementById("filter2");
if (checked == true) {
var option = document.createElement("option");
option.text = value;
x.add(option, null);
y.add(option, null);
}
else {
for (i = 0; i < x.length; i++) {
if (x.options[i].value == value) {
x.remove(i);
y.remove(i);
}
}
}
}
</script>
The else statement obviously removes an item from the list once you uncheck the box.
Now, when you click a check box, rather than adding the item to both lists, it only adds to the second one, and I'm not exactly sure why. Any advice?
You need to create two elements, since in your code you just move the first DOM element to the second select.
var option = document.createElement("option");
var option2 = document.createElement("option");
option.text = value;
option2.text = value;
x.add(option, null);
y.add(option2, null);

Generating text based on selected option in HTML using JavaScript

I am trying to create a site where you select an option from a dropdown list called contactOptions. The options has values ranging from 0 to 8. When the option is selected, I wish for text to appear underneath -- this text is contained within div tags with ID's such as #contact0 for the text corresponding to option 0. These ID's all have display: none by default. I have some JavaScript (below) -- the select tag in my html includes the line onchange = "sortForm()". Unfortunately, the script does not do anything -- the #contact0 remains invisible.
function sortForm() {
var selection = document.getElementById("contactOptions");
var selectedValue = selection.options[selection.selectedIndex].value;
for (var i = 0; i <=8; i++) {
var subobjContact = document.getElementById("contact" + i);
if (i == selectedValue) {
subobjContact.style.display == "block"
} else {
subobjContact.style.display == "none"
}
}
}
Use single equal sign
subobjContact.style.display = "block"
and
subobjContact.style.display = "none"

Remove selected items from other select inputs

I have a problem with select input items.
What I want to achieve is dynamically remove already selected options from other select boxes so that I cannot select same item on multiple boxes. The problem is that elements are loaded in array via AJAX and I need to fill the select input with options after. This makes it so much harder.
In short - How can I make sure that if I select one item in select it will be deleted on all others, but when I select something else the previous item will be shown again and so on...
I have a fiddle as well, this is how far I got: http://jsfiddle.net/P3j4L/
You can try something like this
function updateSelects()
{
$('.selectContainer .select').each(
function (i, elem)
{
// Get the currently selected value of this select
var $selected = $(elem).find("option:selected");
// Temp element for keeping options
var $opts = $("<div>");
// Loop the elements array
for (i = 0; i < selectElements.length; i++)
{
var value = selectElements[i];
// Check if the value has been selected in any select element
if ($selected.val() == value || !$('.select option[value=' + value + ']:selected').length)
{
// if not create an option and append to temp element
$opts.append('<option value="' + value + '">' + value + '</option>');
}
}
// replace the html of select with new options
$(elem).html($opts.html());
if ($selected.length)
{
// set the selected value if there is one
$(elem).val($selected.val());
}
else
{
// new select element. So remove its selected option from all other selects
$('.selectContainer .select').not(this).find('option[value=' + $(elem).val() + ']').remove();
}
}
);
}
see a demo here : http://jsfiddle.net/P3j4L/1/

Categories

Resources