how to choose selected option in select/option in HTML? - javascript

I need to display two select lists with the same options (there are many).
I have the index.html:
<body>
<select class="c_select1"></select>
<select class="c_select2"></select>
</body>
and in another html file (options.html) all the options (only the options):
<option value='AED' title='United Arab Emirates Dirham'>AED</option>
<option value='AFN' title='Afghan Afghani'>AFN</option>
<option value='ALL' title='Albanian Lek'>ALL</option>
<option value='AMD' title='Armenian Dram'>AMD</option>
<option value='ANG' title='Netherlands Antillean Guilder'>ANG</option>
...
<option value='AOA' title='Angolan Kwanza'>AOA</option>
<option value='ARS' title='Argentine Peso'>ARS</option>
<option value='AUD' title='Australian Dollar'>AUD</option>
<option value='AWG' title='Aruban Florin'>AWG</option>
<option value='AZN' title='Azerbaijani Manat'>AZN</option>
Then, using jQuery, I load options inside the two select tags with the same instruction with different class selector:
$(".c_select1").load("options.html");
I'd like to display as default selected option two different values (since I need to show a currency converter).
I've tried in 2 different ways, but any of these works fine (I show the code for just one).
<script type="text/javascript">
$(".c_select1").load("options.html");
$(".c_select1 option[value=ARS]").prop("selected", true);
</script>
or
$(".c_select1").val("ARS");
I don't know why, but I think there is a problem with the .load() of jQuery.
The only solutions that work are 2:
set a timer and execute the second jQuery statement after this timer
use 2 different options.html files one for each select tag, but I think it is not so clever.
Is there a better way to do this dynamically?

Try this:
$(".c_select1").load("options.html", function(){
$(".c_select1").val("ARS");
});
Explained:
The .load() jQuery method requires some time to get the contents of options.html (even if its just a few milliseconds). The browser doesn't wait for it before continuing to run the rest of the javascript logic. The function(){ I added to your .load( method call is some javascript logic that runs AFTER the results have returned (aka a "callback").

Use a callback :
$(".c_select1").load("options.html", function() {
$(".c_select1").val("ARS");
});
$(".c_select2").load("options.html", function() {
$(".c_select2").val("ARS");
});

Actually there is a delay of load method that is why selected item is not working. Like #Joulss said use callback method that should work. You can see the here.
$(function(){
$(".c_select1").load("option.html", function() {
$(".c_select1").val("AFN");
});
$(".c_select2").load("option.html", function() {
$(".c_select2").val("ANG");
});
});
Demo

Related

Not able to fire onchange event dynamically from javascript after selecting options of bootstrap selectpicker

I am using javascript code to select a option on body load as shown in the snippet. This works fine for me.
The issue i am facing in the next step is that i am not able to call onchange event dynamically as soon as the value gets selected in selectpicker.
Code what i have written to select the options dynamically
$('select[name=pname]').val(pnamea);
$('.selectpicker').selectpicker('refresh');
After this i am mapping a simple function addcname1 to onchange event which gives an alert of selected option. but this is not working for me.
Snippet has been provided which explain the problem statment more clearly.
Can you please guide me through where i am going wrong?
Thanks
function openmd2(pnamea){
$('select[name=pname]').val(pnamea);
$('.selectpicker').selectpicker('refresh');
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
}
function addcname1(getval){
var myname = getval.getAttribute('value');
alert(myname)
}
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
<body onload="openmd2('1')">
<select class="selectpicker" name="pname">
<option value="0">select</option>
<option value="1">Mustard</option>
<option value="2">Ketchup</option>
<option value="3">Relish</option>
</select>
</body>
In your code you have to do some small changes to make it running.
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
function openmd2(pnamea){
$('select[name=pname]').val(pnamea).change();
}
function addcname1(getval){
var myname = getval.getAttribute('value');
alert(myname)
}
Here I have just changed the $('select[name=pname]').val(pnamea) with $('select[name=pname]').val(pnamea).change(); to make it running
You can refer this like to get the exact answer
https://jsfiddle.net/Sakshigargit15/j4ccdeaq/17/
It will not give you an alert. Understand it this way.
1- By default, you will have value 1 selected from the first two lines of your function openmd2(pnamea) which will be called on your onLoad().
2- Now in the third line, it gets a call to monitor for the onChange event.
$(document).on('change','.selectpicker',function(){
addcname1(this.options[this.selectedIndex])
});
3- And hence moving forward, if you change the dropdown, you will get the alert. But not the first time (your onload) since there are no listeners waiting for its change.
AFAIK, its working like you wrote it.

jquery select box change on a specific page

I think this should be really easy, but I can't seem to find an answer.
I'm using rails 4 and jquery to identify when one of multiple select boxes is altered on a page, and if so, perform some action.
This is the relevant code in my application.js file:
$('body').on('change', 'select',function(){
*action*
});
The issue I'm having is that this code will pick up a select box change on any page within my application. How do I set things up so that it will only pick up select box changes on a specific page?
Do I do this by creating a new .js file which is specific to my view? If so, how do the file naming conventions work?
there are several ways to do this, but the cleanest seems to be this : add a class to the select you wish to be handled by this function. Let's call this class handlethis. The change your jQuery selector accordingly.
You HTML would look like :
<select name="myselect" id="myselect" class="handlethis">
<option value="1">option 1</option>
<option value="2">option 2</option>
...
</select>
and the JS :
$('body').on('change', 'select.handlethis',function(){
*action*
});
I have an example for you to understand this.I hope it will be helpful to you.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$('select').change(function(){ // when one changes
$('select').val( $(this).val() ) // they all change
})
})
</script>
<style type="text/css">
</style>
<title>HELLO</title>
</head>
<body>
(top of the page)
<select>
<option value="big1">1big1</option>
<option value="big2">2big2</option>
</select>
other content here...
(bottom of the page)
<select>
<option value="big1">big1</option>
<option value="big2">big2</option>
</select>
</body>
</html>
If it is helpful to you then please vote it up.
Provide id for the select box.and use that id for call function
To pick only the select you want, just add an id or a class to the select, your code should look like this :
HTML :
<select id="selector" name="selector">
...
</select>
JS :
$('#selector').change(function() {
*action*
});
The change() function is just a shortcut for on('change').
You can add a new JS file specific to your view, for best practice about it, read this post :
Best way to add page specific javascript in a Rails 3 app?

multiple Bootstrap-select loads very slow

when i try to put multiple selects on website (more than 20) it slows down jquery execution (with stop/continue alert) - is there a chance to optimize the code to load it faster - it takes minutes to load?
sample code
<td><select class="selectpicker" name="ref[240][sub_class]">
<option value=0 selected="selected" >A</option>
<option value=1>B</option></select></td>
<td><select class="selectpicker" name="ref[265][sub_class]">
<option value=0>A</option>
<option value=1 selected="selected" >B</option></select></td>
javascript at the end of the file:
$(document).ready(function() {
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 1
});
});
I was working with bootstrap select too.
This trick solved my problems about bootstrap-select rendering delays on page loading: it seems that on page load, dom element usually render before selectpicker, this is making the CSS "rescale" which cause an horrible effect.
Usually selectpicker takes 500ms for the first rendering, you can force the rendering after the element definition like following avoiding this delay like follow:
<select class="selectpicker" id="your_select">
<option>...</option>
...
<option>...</option>
</select>
<script>
$("#your_select").selectpicker("render");
</script>
Guess it helps :)
In my case it was also totally OK to simple take the
$('.selectpicker').selectpicker();
out of
$(document).ready(function() ...
For me, forcing rendering immediately after the js loading made the select appear practically instantly instead of waiting for the entire page to load:
<script src="~/assets/js/bootstrap-select.min.js"></script>
<script>
$(".selectpicker").selectpicker();
</script>
For me, was problem with bootstrap conflict.
I use this in CMS Joomla, so loaded from me Bootstrap conflict with another(from CMS).
As I removed duplicate files - all start work good
Regards
OrdaSoft team

Adding values to a select box using ajax and organising javascript files

I want to create a page where everything is loaded via ajax calls, so the URL always stays the same. At first the user will be presented with one box with some choices. According to the choice he makes another one will appear and again according to the choice he makes on the second a third will appear. I have successfully created this logic using ajax bit like the following. I am sorry if the code is a bit meshed up, but I am typing the question from a different machine than my code is located, so please be gentle. If you have any problem I will try to provide as much info as I can. So the html
<!DOCTYPE html>
<html>
<head etc....>
<body>
<div class="main-nav">
</div><!--some navigation things here not important-->
<div class=controls>
<div class="select-control1">
<select>
<option selected="selected" value="">Choose one of the following</option>
<!-- adding the django code for this select-->
{% for option in options %}
<option value="{{option.id}}">{{option.name}}</option>
{%endfor%}
</select>
</div>
<div class="select-control2" style="display:none;">
<select>
<option selected="selected" value="">Choose one of the following</option>
</select>
</div>
</div>
</body>
<html>
Also the option1 and 2 in each control1 are prepopulated by a django template for tag (it is a django project).
the ajax calls are triggered on change of each control and the view that is executed from behind sends an array of json_objects
$(".select-control1 select").change(function (){
option = $(this).prop("value");
//Skipping the case where option value is "" for now
$.ajax({
url:'/url/to/view/',
dataType:'json',
type:'GET',
success:onSuccess1
});
});
function onSuccess1(data, status, jqXHR){
$.each(data, function(index, value){
html = "<option value="+value['id']+">"+value['option']+"</option>";
$(".select-control2 select").append(html);
});
$(".select-control2").show();
}
As i said not intrested in error checking or what happens if user checks a different option in select-control1. I do remove them and place the newly gotten ones from the ajax call, just didn't right that right now. My problem are 2 + 1. First of all when the second control is populated with options after the ajax call the "Choose one of the following" option dissappears. Is that the natural behaviour of append?Is there another way?
Second even though i have the selected attribute in the first control in the "Choose one...." option when the page is loaded i don't it won't appear as selected but it will give one of the options loaded from django e.g. option1
Third and final: I am fairly new to ajax and javascript in general, and this kind of programming. I am familiar with procedural languages and can organize them as I want. But Javascript is giving me a hard time. Right now I have a veeery large js file, that will include all ajax and jquery calls of all elements on the page. Is there a way to "modulize" it in a way, to seperate it in different files somehow?Any good links pages books that could give me a guidness?
Thanks in advance!!
This is because of "<option value="+value['id']+>". You missed "
It should be
"<option value="+value['id']+">"+
Or simply try
$(".select-control2").append(new Option(value['option'], value['id']));
If your browser is IE8, the above code won't work. In such cases you have to use something like this,
var opt = new Option(value['option'], value['id']));
$(opt).html(value['option']);
$(".select-control2").append(opt);

Hide/Display tables after selecting different options

I have 2 tables "iu" and "si" and I put a dropdown list for users to select which one they want to see. Once the option is selected, the corresponding table will appear.
Another one is supposed to be hidden but when the page is loaded, default table "si" is shown.
Here is my JavaScript code:
<script>
$(document).ready(function()
{
$('#iu_table').hide();
});
$('#iu').onchange=function()
{
$('#si_table').hide();
$('#iu_table').toggle();
}
</script>
And HTML code:
<select>
<option id="si" selected>SI</option>
<option id="iu">IU</option>
</select>
The table ID is "si_table" and "ui_table" respectively.
I used the code above but it doesn't work. No matter which one I select, only the "si" table is shown.
I hope that someone could help.
You should probably work with the Tutorials of jQuery and familarize yourself with the workings of the libraries.
There are multiple errors in your code:
There is no field onchange. What you want is the change function of jQuery, which is described here: http://api.jquery.com/change/
The code for the change function belongs into the $(document).ready function, so jquery executes it, when the document is loaded. The code has to be executed there, so that the function is called when the select is changed.
You want to work with the change of the select not with the change of the option.
In the body of your change function you hide the one table and toggle other: toggle both, so the first can be shown too, when the option is selected. Also this construct only works for exactly 2 options. If you want more options, you have to work something out like in the answer of Paritosh.
Here is a working sample:
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
$(document).ready(function()
{
$('#iu_table').hide();
$('#selector').change(function()
{
$('#si_table').toggle();
$('#iu_table').toggle();
});
});
</script>
</head>
<body>
<div id="si_table">si</div>
<div id="iu_table">iu</div>
<select id="selector">
<option id="si" selected="selected">SI</option>
<option id="iu">IU</option>
</select>
</body>
There are many ways of achieving this. One is below - I have added id attribute to dropdown control
<select id="myselection">
<option id="si" selected>SI</option>
<option id="iu">IU</option>
</select>
<script>
$('#myselection').bind('change', function(){
if($('#myselection option:selected').attr('id') == "si"){
$('#si_table').show();
$('#iu_table').hide();
}
else if($('#myselection option:selected').attr('id') == "iu"){
$('#si_table').hide();
$('#iu_table').show();
}
});
</script>
There is a method in jQuery which does hide/show matched elements called toggle()
As you need to hide the IU table at first, you may need some css trick for that. So put display:none; for the IU table and do toggle on changing the dropdown values. Working fiddle is here

Categories

Resources