I've got a Problem. I have a Select Option in HTML
<div id="eilig">
<select id="eiligselect" data-role="slider">
<option value="2" selected="selected">n. Eilig</option>
<option value="1">Eilig</option>
</select>
</div>
On page default "n. Eilig" is selected. After I have made a ajax post request (with "Eilig" selected) the select option should go back to default ("n. Eilig")
I have tried it with $('#eiligselect').val(2); but this only change the value back but the select option shows "Eilig" (but internal value is "n. Eilig".
This select is with a data-role "slider" which emulates a on / off switch like in ios.
So I think I have to click that slider with javascript to change it back instead of just change the value.
Do you have a clue? Thanks.
Try this : put selected attribute for option with value="2"
$('#eiligselect option[value="2"]').attr('selected',true);
Bind the event on change for slider on select value change,
$('#eiligselect').on('change', function() {
var activeLabel = $('span.ui-slider-label');
var mySlider = $(this);
var new2 = 'n. Eilig';
var new1 = 'Eilig';
if(mySlider.val() == 1) {
activeLabel.text(new2);
} else {
activeLabel.text(new1);
}
mySlider.slider( 'refresh' ); // .trigger( 'create' )
});
This Code may help you solving your problem,
var eiligselect = $("#eiligselect")[0];
eiligselect.seletedIndex = 0;
Related
I have built a one page website that is broken up by section and each section has ids. My client wants to be able to navigate to each section using a href (#'s) in the search bar like
www.website#gohere
And with my sections, this works well. My problem is they just threw a curve ball and I don't know how to go about doing this -
On my page in a certain section called #labSearch I have a dropdown that is populated from a csv file using jQuery here:
var location = arrayOfEvents[i][0];
if (location != prevLoc)
{
select.innerHTML += "<option id = "+"test" +" value=\"" + location + "\">" + location + "</option>";
}
When a dropdown option is selected, certain divs show up according to the value of the dropdown. They need it so that say the dropdown option is Dallas, when they go:
website.com#Dallas
It takes them to the section with the dropdwin (this is #labSearch) and acts as if the user has selected the Dallas option, meaning the right divs are displayed. I have tried as you can see above giving the options ids, however this does nothing.
How can I make an a href in the search bar select a certain dropdown option? Is this possible?
Why won't the option id work?
Here is my dropdown code in my labSearch section:
<form id="locationForm" style = "width: 70%; margin: auto; padding-bottom: 30px;">
<select class = "form-control" id="selectNumber" style = "">
<option>Choose a location</option>
</select>
</form>
EDIT: Ok at the end of my javascript outside of document ready or anything I have:
var selectHashOption = function () {
console.log("hash changed");
var select1 = document.getElementById('selectNumber');
var parts = location.href.split('#');
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
//select1.onchange();
dropdownChange();
// Trigger the onchange event handler
}
};
window.onhashchange = selectHashOption;
});
</script>
This all works well, except I am unable to call dropdownChange - I get that it is undefined, however I have declared the variable at file scope here:
<script>
var dropdownChange;
Then set it in document ready:
$(".form-control").change(function () {
dropdownChange = function()
{
//stuff
This was explained here Why can I not define functions in jQuery's document.ready()? and I did it as they did. This is BEFORE my hash change window stuff. I can't even call onchange because that is undefined as well. What can I do?
EDIT 2:
I now have my func declared initially at scope level then set here:
dropdownChange = function () {
}
$(".form-control").change(dropdownChange);
In my hash stuff after I tried:
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
select1.onchange();
}
and got same this function is undefined. I then call the function directly with:
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
console.log("HASH="+hash);
select1.value = hash; // Select the option in the dropdown list
dropdownChange();
}
And the function is called but the value (I console.log(this.value)) is undefined here -
You can select an option by setting the value attribute of the dropdown list. I assume that the option value matches the hash part of the URL typed by the user.
For this HTML markup:
<select id="select1">
<option value="Dallas">Dallas</option>
<option value="New York">New York</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Chicago">Chicago</option>
</select>
You can select the option that matches the hash part of the URL with this code:
var selectHashOption = function () {
var select1 = document.getElementById('select1');
var parts = location.href.split('#');
if (parts.length > 1) {
var hash = parts[1]; // Get the hash part of the URL
select1.value = hash; // Select the option in the dropdown list
select1.onchange(); // Trigger the onchange event handler
}
};
window.onhashchange = selectHashOption;
Once the option is selected, I call onchange to trigger the event handler of the dropdown list. Depending on the way the event handler was set, you may need to do it differently, as mentioned in How can I trigger an onchange event manually?.
I needed to monitor the onhashchange event to make it work in my test code, as you can see on the last line of the code sample.
This is the thing I have:
A normal select with a few options...
And the thing is, I do need to click in some other div and when I click on that one, I want the select list to show up as they were clicked normally and then allow the user to choose from the select options
I have some code already
<div onclick="set_select()"></div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
<script type="text/javascript">
function set_select(){
var select = document.getElementById('opts');
return select.active = true;
}
</script>
Not possible with plain html/javascript.
You need some plugin to replace your standard select field with divs and then use your function to trigger that divs. One is selectmenu: https://jqueryui.com/selectmenu/#product-selection
There is a lot more of them available: https://www.google.pl/search?q=js+select+replacement&gws_rd=cr&ei=wN5ZV8SjMIGLsgGP_IboDQ
This is "sort" of possible but not trivial and you will need to possibly do some management of the effect as I do here in the "change" event for the select. Not perfect but perhaps this can give you a start.
Note you MIGHT just want to use the "focus" on the select or, set the visible size as I do here, set the select size on the change to 0 with event.target.size = 0; and so forth.
Revised the markup a bit to allow the click handler:
<div id="clicker">clicker</div>
<select class='form-control' id='opts'>
<option selected disabled></option>
<option>Contacto</option>
<option>Entrevista</option>
<option>Prensa</option>
<option>Conferencias</option>
</select>
Here is the script, as I said, not perfect but you can decide how you handle the change/click events.
window.onload = function() {
var id = "clicker";
var div = document.getElementById(id);
var select = document.getElementById("opts");
div.onclick = function(event) {
console.log('clicker div');
select.size = select.options.length;
select.focus();
};
select.onclick = function(event) {
console.log('opt clicked');
};
select.onchange = function(event) {
console.log('opt change');
var index = event.target.selectedIndex;
console.log(index);
event.target.size = index + 2;
};
}
Here is a fiddle you can use to get you started: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/
Note that if you wish to use the "default" size for the select you can detect that like so:
if (event.target.type == "select-one") {
event.target.size = 1;
} else {
event.target.size = 4;
}
Here is a fiddle with that change and a bit cleaner on the event attachment: https://jsfiddle.net/MarkSchultheiss/mL0b7ubr/1/
I have a series of hidden html form-groups that I want to display based on the values chosen in two cascading select lists. I'm using jQuery to toggle a class on the second list which is then called by an on change event function.
If I hard-code the class, the subsequent form-groups are shown when the on change is fired.
If I use the toggleClass from jQuery to dynamically change the class, the on change function doesn't fire even though the class is toggled correctly.
HTML
<div class="form-group hidden" id="option_env">
<label class="col-xs-12 col-sm-2 control-label" for="ddl_env">Options</label>
<div class="col-xs-12 col-sm-10">
<select name="category" id="ddl_env" class="form-control ">
<option value="-- Select an option --">-- Select an option --</option>
<option value="horse">Tethered horses</option>
<option value="Watercourses">Watercourses</option>
</select>
</div>
</div>
jQuery
var cascadeSelect = $('#ddlcategory');
var optionSelect = cascadeSelect.on('change', function () {
hideAll();
var option = $(this).val();
var childSelect = showOption(option);
return childSelect;
});
$('.option').on('change', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
function showOption(option) {
var returnOption = null;
$('#' + option).toggleClass('chosen hidden')
.find('select').toggleClass('option')
;
var ddl_option = option.substr(option.indexOf('_')+1);
return returnOption = $('#ddl_' + ddl_option);
}
This works insofar as the ddl_env select has the option class added by the jQuery find, however, the $('.option').on('change', function () doesn't fire when the select list item is changed.
If I comment out the line .find('select').toggleClass('option') and manually add the option class to the ddl_env select then it works fine.
I get the same result with jQuery.addClass.
Debugging in Chrome shows that the ddl_env select change doesn't fire the change event when the option class isn't hard-coded.
Classic question.
Replace
$('.option').on('change', function()...
with
$(document).on('change', '.option', function()...
The second syntax works on present and future '.option' items.
This handler will only work on anything with the clas option when the page loads
$('.option').on('change', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
In order for you to get it to work on elements dynamically allocated that class after the page has loadewd you need to delegate the event handler to a higher element, so basically its parent, or if all else fails document
$(document).on('change', '.option', function () {
hideDetail();
var detail = $(this).val();
showDetail(detail);
});
I'm having some trouble creating a JavaScript function using an select element and id link. The function should depend on the selected option/value of the select dropdon.
What I want to do, is call an event function when the select dropdown is clicked, then apply a class to the appropriate id.
The html is this:
<select class="select-trigger" >
<option value="value1">Value1</option>
<option value="Value2">Value2</option>
<option value="Value3">Value3</option>
</select>
And the elements to get a class added:
<div id="value1"></div>
<div id="value2"></div>
<div id="value3"></div>
And my function so far (almost working):
var trigger = document.querySelectorAll('.trigger');
for (var i =0; i < trigger.length; i++) {
var btn = trigger[i];
btn.addEventListener('click', function () {
var id = this.options[this.selectedIndex].value;
document.querySelector('#' + id).classList.toggle('active');
}, false);
}
I think the trouble I'm having is that I'm calling the function using click event listener. I guess I would need to use an onchange function instead?
Also I only want a single div to have an "active" class at any given time. At the moment, the function is adding the class but not removing it when another is selected.
Here's a fiddle http://jsfiddle.net/2Rcjt/1/
Note - I don't want to put any inline onclick JS in my markup.
You can save the last selected option (div) into some property of the select. Then each time user change the option, just toggle class on the last selected option to make it inactive. Code:
var trigger = document.querySelectorAll('.trigger');
for(var i = 0; i < trigger.length; i++){
trigger[i].onchange = function(){
if(this.lastOption) this.lastOption.classList.toggle('active');
this.lastOption = document.getElementById(this.value);
this.lastOption.classList.toggle('active');
};
trigger[i].onchange();
}
Demo.
I wrote this nifty function to filter select boxes when their value is changed...
$.fn.cascade = function() {
var opts = this.children('option');
var rel = this.attr('rel');
$('[name='+rel+']').change(function() {
var val = $(this).val();
var disp = opts.filter('[rel='+val+']');
opts.filter(':visible').hide();
disp.show();
if(!disp.filter(':selected').length) {
disp.filter(':first').attr('selected','selected');
}
}).trigger('change');
return this;
}
It looks at the rel property, and if the element indicated by rel changes, then it filters the list to only show the options that have that value... for example, it works on HTML that looks like this:
<select id="id-pickup_address-country" name="pickup_address-country">
<option selected="selected" value="CA">Canada
</option>
<option value="US">United States
</option>
</select>
<select id="id-pickup_address-province" rel="pickup_address-country" name="pickup_address-province">
<option rel="CA" value="AB">Alberta
</option>
<option selected="selected" rel="CA" value="BC">British Columbia
</option>
<option rel="CA" value="MB">Manitoba
</option>...
</select>
However, I just discovered it doesn't work properly in IE (of course!) which doesn't seem to allow you to hide options. How can I work around this?
Here's what I've got now:
(function($) {
$.fn.cascade = function() {
var filteredSelect = $(this);
var filteredOpts = this.children('option');
var triggerSelect = $('[name='+this.attr('rel')+']');
triggerSelect.change(function() {
var triggerValue = $(this).val();
filteredOpts.detach()
.filter('[rel='+triggerValue+']').appendTo(filteredSelect)
.filter(':first').attr('selected','selected');
}).trigger('change');
return this;
}
})(jQuery);
Which does work in IE, but still has two problems. The .filter(':first').attr('selected','selected'); bit doesn't seem to do anything in IE (it should select the first visible element). Since I've been using appendTo it currently defaults to the last. And the other problem is that since I detach all the elements immediately, you can't have default values in your HTML.
Options cannot be marked hidden. You must use the SelectElement.add(option) and SelectElement.remove(index)...
Here is a link to remove and add select Options in the same order.
How can I restore the order of an (incomplete) select list to its original order?
Here is a link where I made a post for just doing the most simple thing
How to hide optgroup/option elements?
Note in my post the try catch. This is necessary when adding elements expecially when making the site usable in firefox and IE.