Change option in select drop down using javascript - javascript

Firstly apologies if this is a dumb question, I'm rather new to javascript.
I have a select box which is generated by my organisations CMS. I can't change the drop down's content or how it is generated. What I would like to do however is when the page is loaded, change the default (or "selected") option based on a particular value. The other problem is the default is already set in the select drop down is created in HTML. If I could actually change the way options for the select drop down I could easily create some javascript to set the default selection, unfortunately I can't. I'm completely lost. Any assistance would be greatly appreciated.
Code used:
I unfortunately cannot change this:
<select name="q528696:q1" id="q528696_q1" class="sq-form-field"><option value="0" selected="selected">Address adult language literacy and numeracy | 688</option>*More options here*</select>
This is the javascript used. It's very simple:
<SCRIPT> window.onload=updateSelect();
function updateSelect() {
document.getElementById('q528696:q1').value=25;
};
</SCRIPT>

To change a selected option using JavaScript is very simple. But still, I'll break it down.
Let's start off with a simple drop down list with three options. The select tag will have an id of "change".
<select id="change">
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
We want it so that when we press a button "Two" will be the selected option instead of "One". We'll start making our button and making a basic function.
<input type="button" value="Change Selected Option" onclick="changeS()"/>
<script>
function changeS() {
}
</script>
In this function we add the following code
document.getElementById('change').getElementsByTagName('option')[1].selected = true;
Let's take a look at what it's doing.
First, we target the "select" tag with document.getElementById.
Then we get all the elements with a tag name of "option" in the "select" element.
The "[1]" means that we target the second option in the list. The reason we have "1" not "2" is because JavaScript starts counting at "0". If we wanted to target the third option, we would put "[2]".
After that, we just say that we want that specific option in the select tag to be the selected option.I hope it's simple enough and that my explaining was worthwhile :)

I'm answering to this question: How do I change the value of a select element's option? Here's code with comments to help out.
<!--First we'll make a a select element with an option-->
<select>
<option value="Unchanged Value" id="1"></option>
</select>
<!--Now we'll create a button that'll display the value of this option. Refer to the "displayOptionValue" function down below to find out how this is done-->
<input type="button" onclick="displayOptionValue()" value="Display Option Value"/>
<<input type="button" onclick="changeOptionValue()" value="Change Option Value"/>
<!--Here's where the value will display-->
<p id="demo"/>
<script>
//This will get the option's value and display it in the "p" tag
function displayOptionValue() {
var x = document.getElementById("1").value;
document.getElementById("demo").innerHTML = x;
}
//Now we'll change the value
function changeOptionValue() {
document.getElementById("1").value = "Changed Value";
}
</script>
That's what I understand the question to be. If it's not, tell me in the comments and I'll post another answer. Also, if you run the code in your browser, first press "Display Option Value" then "Change Option Value" and then press "Display Option Value" again to see the changes. Once again, if this isn't your question, let me know in the comments.

Related

Selected attribute of select options is not updating automatically

I have multiple selects on my page, each has multiple options.
However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!
Example:
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.
However I found a workaround. To solve this issue we can use this code:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Example:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!
Which is the best approach to solve this?
My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.
But why does this all not happen automatically?
Is it a bug or a feature?
The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.
What do you need the selected-attribute for in your case?
Edit: Based on your comments I made a fiddle
Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want
Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown
I hope it's somewhere along the lines of what you're looking for.
The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)
Note: selected="selected" is not necessary, simply selected attribute will work as well.
When present, select attribute specifies that an option in select should be pre-selected when the page loads.
Also, the pre-selected option will be displayed first in the drop-down list.
Those 2 should be only effects of the selected attribute.
Note the keywords - when the page loads. He is either there or not when a browser loads the page.
If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?
If you simply wanna make element selected there is easier way trough either value:
jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');
Or by index (mind, indexes start at 0 not 1):
document.getElementById("browsers").selectedIndex = "2";
The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.
I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
<option value="-">Please select</option>
<option value="link_2748" selected="selected">Deutsch</option>
<option value="link_2749">Chinese</option>
</select>
<button onclick="return showSelectedOption('select_179');">Show Option Text</button>
<script>
function showSelectedOption(pSelectID)
{
var text;
$("#"+pSelectID)
.find("option")
.each(function(){
if ($(this).prop("selected")) {
text = $(this).text();
}
});
console.log(text);
}
</script>
You can check the value of the select when it changes to see what it has been changed to.
var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
localStorage.setItem('browser', this.value);
});
var browser = localStorage.getItem('browser');
if (browser) {
select.value = browser;
}
<select id="browsers">
<option value="Firefox">Firefox</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
edit
So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded.
I have edited the snippet to reflect this (code is simplified)

jQuery Autopopulate Multiple Select uses text instead of value

I've got a multiple select like this configured to auto-populate:
<select id="multiple-select-box" class="selectivity-input" data-placeholder="Type to search condos" multiple>
<option id="Alabama Grove Terrace" value="Alabama Grove" >Alabama Grove Terrace</option>
<option id="Alden Pines" value="Alden Pines" >Alden</option>
</select>
Upon select I realized the script is submitting the visible Text for each option instead of the value="" for each option chosen.
I tried to change var t=$(this).text(); to var t=$(this).value(); thinking that would grab the value instead of the option text but had the same results. What am I missing?
<script>
$(document).ready(function() {
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).text();
//if()
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
})
$('#multiple-select-box').selectivity();
});
</script>
Ok, so I went to check this selectivity plugin you're using and it converts your select into a series of divs as
<div class="selectivity-results-container">
<div class="selectivity-result-item highlight" data-item-id="Alabama Grove">Alabama Grove Terrace</div>
<div class="selectivity-result-item" data-item-id="Alden Pines">Alden</div>
</div>
you have to change your submit function to get the data-item-id property which corresponds to your original select value like
$("#bySub").submit(function(){
$(".selectivity-multiple-selected-item").each(function(){
var t=$(this).data("item-id");
$(".ml").append("<option selected='selected'>"+t+"</option>");
});
edit
fiddle example
In this line, you are appending options to the select, but you have set no value attribute:
$(".ml").append("<option selected='selected'>"+t+"</option>");
As stated in the comments, the "fetch value" method of a form element in jQuery is:
$(this).val()
You might be confusing it with the JavaScript property:
this.value
...which also works. Both return an array of strings if something is selected and set to "multiple"
To follow up on your comment, I don't see your markup for the selected element with class="ml" thus it's almost impossible to debug why your form isn't submitting the values without seeing the bigger picture (i.e. it may be outside the form element). You could try adding the value property to the select element however jQuery should be able to pick up selected options missing the value property by using the text value instead.

jQuery dropdown option:first selected

I am using some jQuery to populate various dropdowns. I was able to get the jquery to show current value as the first option.
However, I need it to not only show as the first option, but as the currently selected option so that the selection doesn't appear twice in the dropdown.
As shown in the images below, you see the current value is Target. But after clicking the dropdown button, Target is listed twice:
Here is what the current jQuery looks like:
$(function()
{
$eexist = $(this).attr('data-exist');
$('#eexist option:first').val($eexist).text($eexist);
}
Which goes into this modal form dropdown select:
<div id="editCustModal">
<form id="editCustForm" name="editCustForm">
<label for="eexist">Existing/Target</label>
<select class="form-control" id="eexist" name="eexist">
<option></option> // keeping this or not does nothing
</select>
</form>
</div>
The value and the text are the words Target and Existing.
To reiterate, if the current value is Target, then when you click on the dropdown, you should only see Target as the currently selected item AND only see it once.
If you want to select first option then below is the code:
$('select option:first-child').attr("selected", "selected");
But if you want to select the current value then below is the code:
$('#eexist option:first').val($eexist);
this should only work if $eexist exists as value in dropdown
Since you didn't provide much so it's hard to tell..At least provide a jsfiddle link when you ask a question
Do it this way...
$(document).ready(function(){
$("#myselect").change(function(){
var toR = $('<div>').append($('#myselect option:selected').clone()).html();
console.log(toR);
$("#myselect option:selected").remove();
$("#myselect").html(toR+$("#myselect").html());
});
});
Working Fiddle

Jquery Tablesorter filter and external select box

I'm using tablesorter and the filter widget. I found this jsfiddle example that allows filtering entries with a select box (Filter by age). I want to add that select box to my example, but it doesn't work when simply adding
$(".selectAge").bind('change', function (e) {
var cols=[]
cols[3] = $(this).val()
$('table').trigger('search', [cols]);
});
to my example code. Would you please tell me how to get the select box to work?
My example code is a copy from the official example.
It was working, it just didn't look like it. The one problem with the select is that the "reset" option needed an empty string as a value:
<select class="selectAge tablesorter-filter" data-column="3">
<option class="reset" value="">Filter by age</option>
<option>>=25</option>
<option><=25</option>
</select>
Here is an updated demo (all I changed was the select and added the blue theme css).
Update: Just so you know, in the next update, you can just give that select a "search" class name like the other input, and be sure to include a data-column="#" attribute, and have it work automatically when you use bindSearch, so there would not be a need to add extra code:
$.tablesorter.filter.bindSearch( $('#mytable'), $('.search') );

Basic java script to get combobox

I am just starting out with some java script in an asp.net mvc web site.
I current have a form which I am working on.
The first field which the user is prompted with is a combobox / select (in html)
here is the code for it:
<select name="select">
#foreach (var item in Model.networks)
{
<option value="">#Html.DisplayFor(modelItem => item.name)</option>
}
</select>
Now my next field depends on the option which they chose from the combo box.
How can I populate the next field based on the option they chose in the combo box?
So when the user navigates to the page they will ave a combo box populated with all the options. Below that will be empty fields. When the user selects a option in the combo box I want it to then populate the empty fields with the corresponding data from the option which was chosen.
How do I go about doing this?
Please give the newby answer as in the method in which it will be done. I am assuming that I will be using java script for it?
Although I cannot understand your question in detail, I hope I can help you.
HTML
If you have a select element that looks like this:
<select id=dropdown>
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Plain Javascript solution
Running this code:
var element = document.getElementByID('dropdown');
var current = e.options[e.selectedIndex].value;
Would make current be 2. If what you actually want is test2, then do this:
var e = document.getElementById('dropdown');
var strUser = e.options[e.selectedIndex].text;
Which would make current be test2
Put the onChange="getSelectedValue" attribute of the select element and then use the following javascript.
<script>
function getSelectedValue(sel)
{
txtToFill.Text(sel.options[sel.selectedIndex].text);
}
</SCRIPT>
If I understand your question correctly you want to react to a combo box value changing and display different content in your page.
If that is the case what you need to know is
how to handle the change event in the select (drop down)
populate empty fields
Here's how you can register and handle the change event in the dropdown:
$("select[name='select']").on("change", function(){
$('#input1').val("What you want in the input goes here");
});
Here's a fiddle that demonstrates this.

Categories

Resources