I am using simple html code to display a select box when ever i use id attribute for select tag it does not display any item in the list but when ever i remove id attribute it works. but surprisingly the same code works fine in Firefox and Google chrome.
<select id="class_renew" name="class_renew" onchange="class_check()" style="width:310px; height:35px; padding:8px; margin-left:95px;">
<option value="0">Select Your Class</option>
</select>
Help from any one will be appreciated.
Java Script Code
function classInput(data){
var category_vals = document.getElementById("class_renew");
for(var i=0;i<data.length;i++){
category_vals.innerHTML+="<option value='"+data[i].cat+"'>PK-"+data[i].cat+"</option>"
}
}
IDs must match. "class_renew" and "categroy_renew" [sic] are not the same, so of course it won't work ;)
EDIT:
Rather than using .innerHTML, why not do things properly?
category_vals.appendChild(new Option("PK-"+data[i].cat,data[i].cat));
This ensures that you won't have any problems if, for example, any of the items have an apostrophe in them.
Related
Currently I am using jQuery to hide/show select options using following code.
$("#custcol7 option[value=" + sizeValue + "]").hide();
This works fine in Firefox, but doesnt do any good in other browsers. How to I hide options from select in Chrome, Opera and IE?
I just came across this and instead of cloning the entire select over and over I just replaced the options that need to be hidden with span elements and hiding the spans ( though the browser didnt visually show them anyway, I think ) - you may need to change your code ( if complex ) to iterate through the spans for complex logic.
The spans store a reference to the option and replace themselves with it when they need to be shown.
This code can obviously be refactored and prettified.
http://fiddle.jshell.net/FAkEK/12/show/
EDIT #2 ( USE THIS INSTEAD ): It occurred to me that instead of doing all this clone/reference/replace crap, just wrap the option with a span, hide the span, and on show just replace the span with the option again..
http://fiddle.jshell.net/FAkEK/25/show/
I think meder has provided valid answer and here it is slightly changed to reflect what works for me:
$.fn.optVisible = function( show ) {
if( show ) {
this.filter( "span > option" ).unwrap();
} else {
this.filter( ":not(span > option)" ).wrap( "<span>" ).parent().hide();
}
return this;
}
Tested with (long live BrowserStack):
Windows XP: IE 6.0, Firefox 3.0, Safari 4.0, Opera 10.0, Chrome 14.0
Windows 8: IE 10.0 Metro
iOS 3.2 (iPad), iOS 6.0 (iPhone 5)
Android 1.6 (Sony Xperia X10)
jsfiddle
You don't, it's not supported in IE (and assumably not in Chrome or Opera either). You would have to remove the options altogether and add them back later if you want them to be truly invisible. But in most cases a simple disabled="disabled" should suffice and is a heck of a lot simpler than handling the removing and adding of options.
try detach().
you can reattach it later if needed using append() or insertAfter()
To Remove options use:
var opt=$("option").detach();
To show options use:
opt.appendTo( "select" );
Just deleted it and store it in a var in your JavaScript. You can just create the new object when you need it later.
Otherwise try the disabled attribute mentioned above.
/**
* Change visibility of select list option elements
* #param {boolean} stateVal show hidden options if true; hide it otherwise. If not setted then toggle visibility, based on it's current state
*/
$.fn.toggleOptionVisibility = function (stateVal) {
var isBool = typeof stateVal === "boolean";
return this.each(function () {
var $this = $(this);
if (isBool) {
if (stateVal) $this.filter("span > option").unwrap();
else $this.filter(":not(span > option)").wrap("<span>").parent().hide();
}
else {
$this.filter("span > option").toggleOptionVisibility(true);
$this.filter(":not(span > option)").toggleOptionVisibility(false);
}
});
};
the way you did it should work in chrome but nvm.Here is another way
select = $('#custcol7');
select.find('option[value=["'+sizeValue +'"]').remove();
and if you want to show it again:
select.append('<option value="'+sizeValue+'"></option>');
It works perfectly on every browser and its really simple code. The problem is if you want to hide several options it is more typing .. but that can be solved by putting them into variables if they don't change dynamically like that :
var options = '<option value="'+sizeValue1+'"></option><option value="'+sizeValue2+'"></option><option value="'+sizeValue3+'"></option>';
select.append(options);
This way if you have to remove/append on several places you only typed the options once.Hope i gave another interesting option. Best Regards.
There's also the the .load method:
s_parent.change(function(){
s_child.load('./fetch_options.php",{'v',s_parent.val()});
}
The 'fetch_options.php' script would simply print the option tags based on whatever data source you use and the parent value(s) being passed in.
using the solution provided by AuthorProxy, it works fine for IE but when I attempt to do a .val() on the dropdown in firefox I get some funky values that don't make any sense. I have modified their option to include browser specific functionality, hide/show works for firefox.
$.fn.toggleOptionVisibility = function (stateVal) {
var isBool = typeof stateVal === "boolean";
return this.each(function () {
var $this = $(this);
if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
if (isBool) {
if (stateVal) $this.filter("span > option").unwrap();
else $this.filter(":not(span > option)").wrap("<span>").parent().hide();
}
else {
$this.filter("span > option").toggleOptionVisibility(true);
$this.filter(":not(span > option)").toggleOptionVisibility(false);
}
}
else {
if (isBool) {
$this.show();
}
else {
$this.hide();
}
}
});
};
My take is bit different to other answers.
The aim is not to hide the options but just make them disable(to keep the UI consistent).
My Scenario :
I have multiple selects in a form and when an user selects an option in one of the selects the other selects should disable this option and vice versa. User is restricted from selecting the same option which is already selected. We normally disable the option but for IE 7 which does not support it. User also gets an option to add new selects.
Solution :
On load :
If the browser is IE7 then while populating the the selects and disabling the already selected options on other selects I am adding a custom attribute to the option("data-ie7-disabled") and also changing the color of the disabled options to '#cccccc'(which is the standard color for disabled options). This makes the UI look same across browsers.
On Change :
I save the previous option in a local variable(this is saved on focus).
When a user tries to change an option
User selects a complete new option which is not selected in any other dropdown. Then I loop through other selects and change the color and add custom attribute to this selected option on other selects.
When user selects an option that is already selected(The option which has grayed out color). I check if the option has this custom attribute on it first. If it has then > I simply revert the option to the previous one with an error message saying "This option is already selected or BLAH BLAH".
When user changes his existing option to a brand new option which is not selected in any other dropdown's. I again loop through all the other select options and remove the color on it and also the custom attribute.
Hope this helps.
You can use through combinations of var $opt=$('select>option').clone() and $('select option[value="'+val+'"').remove().
There is another example: try this. https://jsfiddle.net/sherali/jkw8fxzf/12/
var $secondOption= $('#second-choice>option').clone();
$("#first-choice").change(function() {
var userSelected = $(this).val();
$('#second-choice').html($secondOption);
$('#second-choice option[value="'+userSelected+'"').remove()
});
You will need to remove it and then add it again for Internet Explorer.
To remove:
$("#custcol7 option[value=" + sizeValue + "]").remove();
To add:
$("#custcol7").append( "<option value='sizeValue'>sizeValue</option>" );
Note that you need to have sizeValue also in the option text, to actually see something.
You can also replace the html within the select.
Html:
<input id="Button1" type="button" value="hide option" />
<select id="foo">
<option >stuff</option>
<option >stuff2</option>
</select>
Jquery:
$("#Button1").change(function () {
$('#foo').html('<option >stuff</option>');
});
Not exactly what you want, but perhaps it helps. For smaller dropdowns, it is definitely easier.
In IE 11(Edge), the following code is working.
$("#id option[value='1']").remove();
and to ad back,
$('<option>').val('1').text('myText').appendTo('#id');
meder's solution is what I went with for this, but with a small tweak to prevent it from wrapping an option in a span that was already in a span:
$.fn.hideOption = function() {
this.each(function() {
if (!$(this).parent().is('span')) {
$(this).wrap('<span>').hide();
}
});
};
$.fn.showOption = function() {
this.each(function() {
var opt = $(this).find('option').show();
$(this).replaceWith(opt);
});
};
<html>
<head><script>
$(document).ready(function(){
$("#l1").change(function(){
var selectedId=$("#dl1 option[value='"+$(this).val()+"']").attr("id");
$("#dl2 option[data-id ='"+selectedId+"']").removeAttr('disabled');
$("#dl2 option[data-id !='"+selectedId+"']").attr('disabled','disabled');
$("#l2").val("");
});
});
</script></head>
<body>
<label for="l1">choose country</label>
<input list="dl1" name="l1" id="l1" type='select'>
<datalist id="dl1" name="dl1">
<option value="India" id=1>
<option value="US" id=2>
<option value="Germany" id=3>
</datalist>
<br>
<label for="l2">choose City</label>
<input list="dl2" name="l2" id="l2" type='select'>
<datalist id="dl2">
<option value="New Delhi" id="11" data-id="1">
<option value="Washington DC" id="12" data-id="2">
<option value="Berlin" id="13" data-id="3">
<option value="Mumbai"id="14" data-id="1">
<option value="NewYork" id="15" data-id="2">
<option value="Munich" id="16" data-id="3">
</datalist>
</body>
</html>
You can use this:
$("#custcol7 option[value=" + sizeValue + "]").css({display:'none'});
It works fine on all browsers except Safari and Opera. I'm searching for another best solution :)
How can I hide the part of the text written inside of the option?
I've tried the following:
<select name='what'>
<option value='some value'>Value to be shown <span class='hide'>value to be hidden</span></option>
....
</select>
And here is the CSS.
.hide{ visibility : hidden; }
But it doesn't seem to work. I've also tried display:none instead of visibility:hidden but that doesn't work either.
P.S: Why I want to do this? I want to do this because I want the hidden text to be included in the search.
UPDATE I am well aware that it may be achieved using the html5 meta tags, but unfortunately that I can't use here as I am using Jquery plugin called Chosen and it doesn't support the search over meta tags.
In order to add extra data to your option, e.g. for search, you may use the value or extra attributes of the option element.
For example,
<option value="value to be hidden" data-meta="value to be hidden">Value to be shown</option>
HTML
<select>
<option value="value to be hidden1" data-meta="value to be hidden11">Value to be shown1</option>
<option value="value to be hidden2" data-meta="value to be hidden22">Value to be shown2</option>
<option value="value to be hidden3" data-meta="value to be hidden33">Value to be shown3</option>
</select>
<div class='output'></div>
JS
$(document).ready(function(){
$('select').change(function(){
$('.output').html($('select option:selected').val()+'<br/>'+
$('select option:selected').data('meta'));
});
});
http://jsfiddle.net/uHY5P/
You may introduce as many attributes as you want with the prefix "data-" and retrieve them by calling jQuery.data('yourCustomAttr')
You can't do this. <option> tag cannot contain any other tags. Use Select2
It's been a while since you posted your question but it may help someone in the future. I went through exactly the same process in the past few days.
I needed to search for select options with or without special characters using jquery Chosen plugin (ver. 1.1.0).
I have a drop down with wine producers which includes names with foreign characters like Château Bénitey. In this case free text search should find the producer with "château bénitey" and "chateau benitey" keywords.
This is how I achieved it:
I used PHP to dynamically convert special characters to their equivalents eg. "â" => "a".
I created an extra attribute in <option> tags in html called data-search-text="Château Bénitey Chateau Benitey".
Then I patched Chosen plugin to read the data-search-text value instead of option text.
In SelectParser.prototype.add_option method I added a new property to store attribute values.
this.parsed.push({
array_index: this.parsed.length,
options_index: this.options_index,
value: option.value,
text: option.text,
html: option.innerHTML,
selected: option.selected,
disabled: group_disabled === true ? group_disabled : option.disabled,
group_array_index: group_position,
classes: option.className,
style: option.style.cssText, // extra comma ;)
searchTextAttribute: option.getAttribute('data-search-text') // this is the line I added
});
Then I modified AbstractChosen.prototype.winnow_results method:
Replace:
option.search_match = this.search_string_match(option.search_text,
regex);
With:
var textToSearch = option.search_text;
if (option.searchTextAttribute) {
textToSearch = option.searchTextAttribute;
}
option.search_match = this.search_string_match(textToSearch, regex);
I have multiple dropdowns in my advanced search so only the selects that have data-search-text attribute populated will behave that way.
I also had to remove the feature that highlights matched parts of option text as it was breaking it.
if (searchText.length) {
startpos = option.search_text.search(zregex);
text = option.search_text.substr(0, startpos + searchText.length) + '</em>' + option.search_text.substr(startpos + searchText.length);
option.search_text = text.substr(0, startpos) + '<em>' + text.substr(startpos);
}
Make sure you initialise the Chosen plugin with the following setting, otherwise it will search from the beginning of search only and the converted text won't be matched.
$('.your-select').chosen({search_contains: true});
Working like a switch on Chrome (v27.), FF (v21.), and IE9.
I cannot test on other browsers.
As it doesn't refers to anything else than HTML, I am about to think that it works like this, on any browser. But, I'd like to be sure.
Any help please ?
TO CANCEL SELECTED COLOR :
<select name="transparenceStrips" id="transparenceStrips" size="1" onclick="transpbandeau()">
<option value="transparent">CLICK HERE</option>
</select>
here is the jsfiddle
Is not a typical usage of a select, this UI can confuse users; I think it will be better using a button.
Something like:
HTML:
COULEUR fond page
<input name="colorFond" id="colorFond" class="color1" value="FFFFFF" size="5" onchange="setBack()">
<br>CANCEL :
<button onclick="transp()">CLICK HERE</button>
Code:
function transp() {
document.getElementsByTagName('BODY')[0].style.backgroundColor = "";
}
function setBack() {
document.getElementsByTagName('BODY')[0].style.backgroundColor = '#'+document.getElementById('colorFond').value;
}
Here is a simple fiddle: http://jsfiddle.net/IrvinDominin/gVH3n/3/
is it crossbrowser?
It's not cross browser, try testing it on an Android Chrome, you'll find that it tries to open the options list in addition to resetting the background color.
The other answer had given a better way to do what you want to do.
Hi I have an ajax script which validates the users information put into textboxes. This is working fine in Internet Explorer, but in FireFox I get an error in getting the gender from a listbox. I have got the gender to be placed into a hidden textbox, for easier processing. The error I get in FF is
dd is null
[Break on this error] theindex = dd.options[dd.selectedIndex].value;
My function in javascript is below, this is loaded on body load or once the gender selected is changed,
function get_gender()
{
{
var dd = document.getElementById("gender_select");
theindex = dd.options[dd.selectedIndex].value;
thevalue = dd.options[dd.selectedIndex].text;
}
document.getElementById("gender_text").value = thevalue;
}
One other problem I am having is hidding a div box, this works fine in every other browser but not IE. It should only show the div box once an error is given, but in IE the div box is always shown.
I am using this line to do this:
document.getElementById("username_div").style.visibility = "hidden";
Rather than pasting all my code the live page can be viewed at
http://elliottstocks.com/assignment/sign_up/
Ignore the login box, this works fine.
Any comments/help will be appreciated. Thanks alot =)
getElementByID requires the HTML element to have an ID, just a name isn't good enough.
<select name="gender_select" id="gender_select" onChange="get_gender()">
<option>Male</option> <option>Female</option>
</select>
For the null error change:
<select onchange="get_gender()" name="gender_select">
to
<select onchange="get_gender()" name="gender_select" id="gender_select">
document.getElementById is looking for an element in the DOM that has a given id attribute. The reason it works in IE is because it allows selecting by name attribute as well.
For your second problem, you may want to try display = 'none'; for your element. Be aware that this behavior is different from visibility = hidden.
I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE:
var drop= function(id)
{
if(document.getElementById("select1").value == "Ficha de pediatria"){
top.location.href = "print.jsp?id="+id+"&type=2";
}
else if(document.getElementById("select1").value == "Ficha normal"){
top.location.href = "print.jsp?id="+id+"&type=1";
}
}
<select id="select1" name="select1" onChange="drop(id);return false;">
<option>Imprimir:</option>
<option>Ficha de pediatria</option>
<option>Ficha normal</option>
</select>
I trimed this as it had more JSP code but it' remained the same. Anyone got any idea why it's not running on IE?
[EDIT] Sorry. I introduced an error with my first post by not carefully looking at how you are constructing your url. I shouldn't have removed the id parameter. I've updated the code and it should work now.
Try this instead:
function drop(ctl,id)
{
var value = ctl.options[ctl.selectedIndex].value;
if(value == "Ficha de pediatria"){
window.top.location.href = "print.jsp?id="+id+"&type=2";
}
else if (value == "Ficha normal"){
window.top.location.href = "print.jsp?id="+id+"&type=1";
}
}
<select id="select1" name="select1" onChange="drop(this,id);return false;">
<option>Imprimir:</option>
<option>Ficha de pediatria</option>
<option>Ficha normal</option>
</select>
[EDIT] A bit of explanation...
I think the issue is how it is accessing the DOM. I don't think that IE has a value property on a select. I think you have to get at it via the selected option. Also, I'm not sure that there is a top property in the global namespace, but you should be able to get at it via window.top to set the location. Finally, I made a slight improvement in that by specifying this as the argument, you can skip the element lookup and reference it directly from the control passed as the argument.
IE doesn't like the way you're grabbing the value of the select
document.getElementById("select1").value
This is saying "give me the text that's in the value attribute of the selected option in the select element with the id select1. Your options don't have any values. When Firefox and Safari encounter this ambiguity, they return the text of the selected option. When Internet Explorer encounters this ambiguity, it returns a blank string. Your javascript would work as is if you did something like
<select id="select1" name="select1" onChange="drop(this,id);return false;">
<option value="Imprimir:">Imprimir:</option>
<option value="Ficha de pediatria">Ficha de pediatria</option>
<option value="Ficha normal">Ficha normal</option>
</select>
If that's not possible, you'll want to grab the text of the option that's selected.
var theSelect = document.getElementById("select1");
var theValue = theSelect.options[theSelect.selectedIndex].text
Finally, while not your direct question, a the hard coded select1 isn't the best way to get at the select list. Consider using the this keyword
function foo(theSelect){
alert(theSelect.options);
}
...
<select id="whatever" onchange="foo(this);">
...
</select>
This is a bit more generic, and you'll be able to use your function on a select with any ID.
It's not that IE "doesn't have .value" of a <select> element, it's that you haven't specified any values for your <option> elements. Firefox, Safari, and co. are likely protecting you from this mistake. Nevertheless, your element should be constructed as:
<select ...>
<option value="Imprimir">Imprimir:</option>
<option value="Ficha de pediatria">Ficha de pediatria</option>
<option value="Ficha normal">Ficha normal</option>
</select>
...and you'll see more standard x-browser behavior for the <select>'s .value property.
I see two possible reasons.
1 - The way the function is declared. I've never seen it like that though I guess it works.
Maybe try the following and see if it still does not work:
function drop(id)
{
// same code
}
2 - The return false in IE does not always behave properly (trust me, it depends on the computer) So instead of returning false, try:
onChange="drop(id);event.returnValue=false;return false;"
If possible create a method like this one:
function CrossBrowserFalse()
{
if(IE) // use whatever you want to detect IE
{
event.returnValue = false;
}
return false;
}
and then in your methods you can use:
onChange="drop(id);return CrossBrowserFalse();"
...yeah, IE is weird sometimes (often)
If these two fail, at least make sure your drop function is called by putting some alerts in there or breakpoints if your IDE supports it for javascript.