I need to change the 'selected' attribute of a html option element within a select object using javascript.
I already tried this: Solution
This is what I have:
.cshtml
<div class="form-group form-group-default" id="divStateEUA">
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
#foreach (var state in ViewBag.EUAStates)
{
<option>#state</option>
}
</select>
</div>
javascript
<script>
$(document)
.ready(function () {
CheckState();
});
function CheckState() {
if (selectedText == 'Estados Unidos') {
var element = document.getElementById('listStateEUA');
element.value = 'Chicago';
}
}
</script>
rendered html:
And still not working. Any ideas?
You are missing value attribute in the option tag of select.
Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :
#foreach (var state in ViewBag.EUAStates)
{
<option value="#state">#state</option>
}
and now in your jquery code, you should be able to do :
function CheckState() {
if (selectedText == 'Estados Unidos') {
$("#listStateEUA").val("Chicago");
}
}
You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>
function CheckState() {
var element = document.getElementById('listStateEUA');
element.value = 'chicago';
}
CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA">
<option value="nevada">nevada</option>
<option value="chicago">chicago</option>
<option value="arizona">arizona</option>
</select>
As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
Answer found here: select2 plugin get and set values
Related
I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach
I am trying to pass value stored inside a div tag to a javascript function based on the onchange property of a drop down menu in HTML.
But nothing is being passed. Undefined error is shown.
Here my code:
Suppose $temp_c has a value 30.
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value,temperature_div.value,temperature_div.name); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
And JavaScript
function choose_temperature(conv, value, name) {
alert(conv);
alert(value);
alert(name);
}
Where did I go wrong??
In JavaScript you can't just use temperature_div as a variable and assume it will be the object with id temperature_div. There are functions for fetching elements from the DOM. In plain JavaScript: document.getElementById('temperature_div') will return the element. If you're using JQuery, then $('#temperature_div') will do a similar thing.
Edit:
Try this function:
function choose_temperature(conv) {
alert(conv);
var element = document.getElementById('temperature_div');
alert(element.innerHTML);
alert(element.attributes["name"].value);
}
Called by: choose_temperature(this.value);
Edit: Changed to use innerHTML and attributes["name"].value instead of value and name. I'm assuming that these are what are wanted.
First of all you have used the parameter 'value' which I think is a key word and better not to use.
and I am assuming you are referring to the 'name' html attribute in the 'temperature_div', which you have not defined. I am putting a name attribute just for the sake of understanding.
<html>
<script type="text/javascript">
function choose_temperature(conv, t_value, name)
{
alert(conv);
var div = document.getElementById("temperature_div");
alert(div.innerHTML);
alert(div.getAttribute("name"));
}
</script>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(this.value); ">
<option value="celcius" selected>°C</option>
<option value="farenheit">°F</option>
</select>
Use jquery instead, it is easier.
Get value inside a div as: $('#temperature_div').html() Or $('#temperature_div').text()
You can write onchange for a select box as:
$(document).on('change', '#ddl_temptype', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Or like this
$('#some_id').on('change', function() {
// Write your function here
var div_value = $('#temperature_div').html();
var select_val = $(this).val();
alert(div_value);
});
Use getElementById() in javascript
<span id="temperature_div"><?php echo $temp_c; ?></span>
<label for="ddl_temptype"></label>
<select id="ddl_temptype" name="ddl_temptype" onchange="choose_temperature(); ">
<option value="celcius" selected> °C</option>
<option value="farenheit"> °F</option>
</select>
function choose_temperature()
{
var value=document.getElementById('temperature_div').innerHTML; //to get html inside span
var conv=document.getElementById('ddl_temptype').value;
alert(conv);
alert(value);
}
I am looking for a simple .js solution. I have two dropdown buttons - code:
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01">child_option_01</option>
<option value="opt02">child_option_02</option>
<option value="opt03">child_option_03</option>
<option value="opt04">child_option_04</option>
</select>
Now I need to accomplish this:
When option_01 in #parent is chosen ---> make available only child_option_01 and child_option_02 in #child dropdown
When option_02 in #parent is chosen ---> make available only child_option_03 and child_option_04 in #child dropdown
I tried some solutions I found online but so far no luck. I have a very basic .js knowledge.
Link to FIddle: http://jsfiddle.net/q5kKz/343/
Help will be appreciated.
Taking the next step with your fiddle, this will do (almost) what you want:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
}).change();
Notice the attribute selector: "option[value='opt01']" - that says "any options with value of opt01".
You should probably expand that selector to be "#child option[value='opt01']"
Using a "basic" programming method, you could do this for multiple options:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
$("option[value='opt02']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
// Adding multiple options here. This is a bad method for maintainability
}).change();
A better way to go would be to assign some sort of other attributes to the options that should show depending on which parent is selected. One example is using a class that matches the parent value desired - which would require modifying your child list like so:
<select name="child_dropdown" id="child">
<option value="opt01" class="option_01">child_option_01</option>
<option value="opt02" class="option_01">child_option_02</option>
<option value="opt03" class="option_02">child_option_03</option>
<!-- The below option would show whenever the parent is on option 2 OR 3 -->
<option value="opt04" class="option_02 option_03">child_option_04</option>
</select>
But then your script could be much more usefully constructed like so, and wouldn't need to be changed if you added / changed options:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
}).change();
This still leaves the problem of the list option hiding, and the select can still be set to a "hidden" value. This would need to be addressed somehow. Something like the below:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
var child_val = $('#child').val();
// If the selected option is not visible...
if ($('#child').find(":selected").not(":visible")) {
// Set it to the first option that has the proper parent class
$("#child").val($("#child option." + val + ":first").val());
};
}).change();
With newer versions of jQuery you could do something like:
var group1 = $("#child").find("option[value='opt01'], option[value='opt02']");
var group2 = $("#child").find("option[value='opt03'], option[value='opt04']");
$('#parent').change(function() {
var selected = $("#parent").find(":selected").text();
if (selected == "parent_option_01") {
group1.prop("disabled", false);
group2.prop("disabled", true);
} else {
group1.prop("disabled", true);
group2.prop("disabled", false);
}
}).change();
The other people may have it right. But when you want to make changes you have to change a bunch of JS code. I think this is a better approach. In our child HTML we add a data attribute to show what values of parent will make this child option show. This way if we ever need to add more elements or change what ones make the children appear we can just change the HTML and it leaves our javascript a lot cleaner.
http://jsfiddle.net/q5kKz/348/
var parent = $("#parent");
var child = $("#child");
var val;
$('#parent').change(function() {
//Get value of parent
val = $("#parent").val();
//cycle through children and find which data show matches the parent
child.children().each(function(){
var c = $(this);
//Jquery's .data wasn't working for some reason
if(c.attr("data-show") === val){
c.show()
}else{
c.hide()
}
})
}).change();
In the HTML
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01" data-show="option_01">child_option_01</option>
<option value="opt02" data-show="option_01">child_option_02</option>
<option value="opt03" data-show="option_02">child_option_03</option>
<option value="opt04" data-show="option_02">child_option_04</option>
</select>
I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.
My code:
function getCountry(var name) {
if(name==geoip_country_name()) {
return "selected";
}
}
Then I need to set the selected attribute of the option list.
I tried this:
<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>
But this is not correct.
Basically I want to set selected attribute value using JavaScript function
How do I do that?
Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.
<script>
window.onload = function(){
document.getElementById("country").value = geoip_country_name();
}
</script>
<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>
Basically you can do it like this:
<html>
<body>
<select id="country">
<option id="germany" value="Germany">DE</option>
<option id="uk" value="UK">UK</option>
<option id="usa" value="USA">USA</option>
</select>
<script>
var selectedCountry = 'uk'; //getCountry
var index = document.getElementById(selectedCountry).index;
document.getElementById("country").selectedIndex=index;
</script>
Start the script after your select is rendered.
Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...
The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:
var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
if(select.options[i].value == country)
select.selectedIndex = i;
}
If you are using JQuery following line should solve your problem:
$('select').val(geoip_country_name());
If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.
I have a main select "main", and a list from 2 till 9, depending the situation, of more selects.
What if I want to change the value in all this secondary selects, with the same value that the main select?. So the main select will change more than 1 select at the same time:
So, I have got the main select:
<select name="main" id="main" onchange="document.getElementById('item').value = document.getElementById('main').value">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
And the next selects are made in php inside a loop, so I will have 2,3,4,5,..,9 selects depending the situation. Each of them with a different name (because I use this name in POST)
<select name=item_".$itemnumber." id="item">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
With this I want to have the possibility to select in one time the option for all the selects, but maintaining the possibility to change only some of the selects.
I made it work like that:
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].id == 'item' && theForm[z].id != 'main'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
But I dont know if thats the best way, I heard here that jQuery would be easier, so I would like to know how to make it in jQuery, please.
What I understand is, you have a <select> dropdown, and on change of the text in this one, you want to change the the selection in one or more of other dropdowns on your screen. Am I right?
If this is the case, then you have to have a javascript function and call this in the onchange of the <select>.
In this javascript function, you have to set the selected value of all the dropdowns you want.
If this is not what you want, Can you please rephrase your question and tell us what you exactly you want?
EDIT
function setElement()
{
var selectedValue = document.getElementById("main").value;
selectThisValue(document.getElementById("child1"), selectedValue);
selectThisValue (document.getElementById("child2"), selectedValue);
}
function selectThisValue(selectElement, val)
{
for ( var i = 0; i < selectElement.options.length; i++ )
{
if ( selectElement.options[i].value == val )
{
selectElement.options[i].selected = true;
return;
}
}
}
Call setElement() in your onchange of the main. This function gets the selected item from the main <select> and selects the items in the other dropdowns that have the same value.
You call the selectThisValue function once for every select you need to change.
Change the ids as per your code.
Never put the same id in all the select elements... ID is supposed to be unique for elements in a page.
change your html to look like
<select id="main" class="master">....</select>
<select id="test1" class="child">....</select>
<select id="test2" class="child">....</select>
<select id="test3" class="child">....</select>
<select id="test4" class="child">....</select>
Class attribute for multiple elements can be the same.
Your function needs to be modified to look like this
(i havent tested this, but should work..)
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].className == 'child'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
by the way, do the options inside these select boxes vary? if so, you'll have to match by value rather than index
EDIT: here's the code i wrote later.. modify it to suit your need
<html>
<head><title>select change cascade</title></head>
<body>
<select id="main" class="master"><option value="1">book</option><option value="2">cd</option></select>
<select id="test1" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test2" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test3" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test4" class="child"><option value="1">book</option><option value="2">cd</option></select>
<script type="text/javascript" src="./selectchange.js"></script>
</body>
</html>
and in selectChange.js
var main = document.getElementById("main");
main.onchange = function (){
sels = document.getElementsByTagName("select");
for(z=0; z<sels.length;z++){
if(sels[z].className == 'child'){
sels[z].selectedIndex = this.selectedIndex;
}
}
}
I don't see any question marks.
The only issue I see is that you should use .selectedIndex instead of .value.
jQuery solution:
$(".selectorClass").each(function(index, selectorToUpdate){
selectorToUpdate.selectedIndex = $('#main').selectedIndex;
});
Put this in a function and call that function for onchange.