Need function to run on selecting an option in dropdown box - javascript

Hi I know this has probably been asked before.
I have this code so far:
<select name="cashfunction" type="text" id="cashfunction" title="Select Function"
class="required">
<option id="cashfloat">Cash Float</option>
<option id="cashvari">Cash Variance</option>
<option id="expenditure" value="1">Expenditure</option>
<option id="cashbanked" value="2">Cash Banked</option>
</select>
<script>
function bankCategory()
{
document.getElementById('bankcat').style.visibility='visible';
$('.dynamicreq').addClass("required");
}
function expendCategory()
{
document.getElementById('expend').style.visibility='visible';
$('.dynamicreq').addClass("required");
}
$('#cashfunction').on("change", function() {
if($(this).val() === 1)
{bankCategory();
}
if($(this).val() === 2)
{expendCategory();
}
}
);
</script>
I need the divs by id to remain hidden until selected.
At the moment both divs are hidden but remain hidden when I select from the menu.

I believe the reason your current code doesn't work is that you are using === to compare the string returned from .val() with numeric values 1 and 2. The === operator checks that the operands have the same value and type, so won't return true. Either use == instead, which does some implicit type conversion, or, better, compare strings with strings rather than relying on type conversion:
if($(this).val() === "1")
If it were my code I would not define separate functions for each value though, I'd try to make my code a bit more generic by having the option elements somehow specify the related divs:
<select name="cashfunction" type="text" id="cashfunction" title="Select Function" class="required">
<option id="cashfloat">Cash Float</option>
<option id="cashvari">Cash Variance</option>
<option id="expenditure" data-assoc="bankcat" value="1">Expenditure</option>
<option id="cashbanked" data-assoc="expend" value="2">Cash Banked</option>
</select>
<div id="bankcat" class="optional">Bank Category div</div>
<div id="expend" class="optional">Expenditure Category div</div>
...and then use JS something like this:
$('#cashfunction').on("change", function () {
$("div.optional").hide();
var associatedDivId = $(this).find("option").filter(":selected").attr("data-assoc");
if (associatedDivId) {
$("#" + associatedDivId).show();
}
});
Demo: http://jsfiddle.net/b372b/
Note that in my demo I used display:none instead of visibility:hidden because then I was able to just use .hide() and .show(), but if you want to keep using visibility it would be:
$("#" + associatedDivId).css("visibility", "visible");
You didn't actually include the markup for your divs in the question, but if you give them all a common class it makes it easy to hide them again if the selection is changed. (Your question never specifically says that you want to hide them again, so if not obviously you can just remove the .hide() statement.)
If using data- attributes seems too complicated you could just put the id of the associated divs in the value property, and then the JS would be:
var associatedDivId = $(this).val();
Regarding where you've coded $('.dynamicreq').addClass("required"); - I assume those .dynamicreq elements are within the divs that are being hidden or shown, but note that .addClass() will add the new class to all of them including the hidden ones.

Related

When options disabled, select not works on IE 11 - jQuery [duplicate]

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 to sset the default setting

i know this is very dumb question but i m stuck in this problem i create a form in jsp and in form i use a dropdown list which provide the option for change the css on Labels of form like ..."Left Align, Right Align, None" starting two optionare working properly "None" option functionality is when i selected this option so the css which is applied by two option is removed and the default setting of this form is show............ please suggest me how i do it ...............here i m showing my code
JavaScript Code
function placement() {
var dropVal = $('#styleField').val();
if (dropVal == "la") {
$("._check").each(function(index) {
$('label').css("float", "left");
});
}
if (dropVal == "ra") {
$("._check").each(function(index) {
$('label').css("float", "right");
});
}
if (dropVal == "de") {
// $("._check").each(function(index) {
// $('._check').find('checkbox').css("float" , "left")
// $("float").remove();
});
}
}
this is my code and _check is a class which is applied on checkbox
Html Code
<select id="styleField" name="styleOfField" class="form-control select2me" data-placeholder="Placement Of labels" onclick="placement();">
<option> - </option>
<option value="la"> Left Aligned </option>
<option value="ra"> Right Aligned </option>
<option value="de"> Default </option>
</select>
so please help me ...Thanks in advance
To reset the float, you want to set float: none:
$('label').css('float','none');
But your code has other issues. You are iterating through each _check for no apparent reason. $('label') will target all labels, regardless of the presence of any ._check element.
Are you looking for label inside a ._check element? In that case, you can select them with the descendant selector, , and you don't need to iterate over the results, .css works across entire sets:
$('._check label').css('float','none');
You appear to have two options for the default behavior. One which has the value "de", and one which doesn't have a value at all. The latter will not match any condition in your placement function.
Furthermore, the code you've shown us has unmatched brackets, but I suppose that may just be a pasting issue.
You could also do this with classess. That way you don't have to manually set float: none, but you could simply omit setting a float when none is needed.
CSS
.la { float: left; }
.ra { float: right; }
JavaScript
function placement() {
$('._check label')
.removeClass('la ra')
.addClass($('#styleField').val());
}
Some notes on your commented out attempts:
$('._check').find('checkbox') would look for all <checkbox/> children of a class="check" element. If you want to search for an <input type="checkbox" /> you may use the :checkbox selector.
$('float').remove() would look for all <float/> elements in the document and remove them.
Update addressing your comment
Now that you've clarified that you want all labels with a _check class, my code above doesn't do that. It selects all labels that are the descendants of an element with a check class. Your code selects all labels regardless of whether they have a check class, and does so repeatedly because of your iteration.
If you truly want all labels in the document that has a class named _check, the code would be:
$('label._check').css('float','none');

How do you put the value of a select-element into a textarea?

I'm trying to add a function where you select a color of a shirt from a select-element and add it to the textarea when you press the button.
Also if anyone can give advice to do the same with a group of radio buttons, that would help a lot.
JavaScript
function addShirt() {
buildStr += document.shirtInfo.color.value;
}
HTML
<form name="shirtInfo">
<h1>Shirts</h1>
<select name="color">
<option>White Shirt</option>
<option>Black Shirt</option>
<option>Grey Shirt</option>
</select>
<input type="button" name="complete" value="Submit" onclick="addShirt()"/>
<textarea name="receipt" rows="10" cols="15"></textarea>
Please use IDs in your HTML. Anyone trying to access your DOM will find it a lot easier to modify if they can just call an ID.
So, all you really want to do is add to the value of the textarea.
// First, define the type of variable that you want (I chose an array)
// You don't have to, but it's easier for me to iterate over
var buildstr = [];
// I'm adding this event listener on the Javascript side
// so it doesn't require you changing the HTML to modify it
document.shirtInfo.complete.addEventListener("click", function(e) {
// Take the value of the dropdown and add it to the end of the array
buildstr.push(document.shirtInfo.color.value);
// Then overwrite the value of the textarea with the array
document.shirtInfo.receipt.value = buildstr;
})
You can use the getElementsByName javascript function to access your textarea in javascript. Once you have access to the DOM element representing your textarea in javascript, you can use the innerHTML property to change its content.
function addShirt() {
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value;
}
You should take note that getElementsByName returns an array. That is the reason why you have to take the first element of that array. You could also use getElementById, which returns only one element, after having added a unique id attribute to your textarea.
To make your results clearer, you might want to add a new line after each color you add :
document.getElementsByName("receipt")[0].innerHTML += document.shirtInfo.color.value + "\n";

hide the text inside select control

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});

javascript and <option>

I do have the following JavaScript.
<form>
<select id="sel">
<option value="1">item_1</option>
<option value="2">item_2</option>
<option value="3">item_3</option>
</select>
<div id="show"></div>
</form>
<script type="text/javascript">
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value;
};
</script>
If I click onchange a new value (here: 1,2, or 3) is shown in the div "show". This is working fine. But my problem is that I want a different value to be shown but the value (1,2, or 3) should be submitted. The item has a unit like kg, pound, m, m², ....
I want something like that:
<option value="1" value2="kg">item_1</option>
I changed value to value2 in <script> but it didn't help.
show.innerHTML = this.value2;
How can I get it to work?
if you apply what #Simon said, you can try the following:
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.options[this.selectedIndex].getAttribute('value2');
}
Revised HTML:
<form>
<select id="sel">
<option value="1" data-unit="kg">item_1</option>
<option value="2" data-unit="kph">item_2</option>
<option value="3" data-unit="m2">item_3</option>
</select>
</form>
<div id="show"></div>
The revised HTML uses the custom, and in HTML5 valid, data-* attribute to store the units. I've also moved the div out of the form, but that's an entirely personal inclination, and one that you don't have to maintain (obviously...).
Amended JavaScript:
var sel = document.getElementById('sel');
sel.onchange = function() {
var show = document.getElementById('show');
show.innerHTML = this.value + this.options[this.selectedIndex].getAttribute('data-unit');
};
JS Fiddle demo.
The JavaScript looks for the option within the this node with the selectedIndex, and then uses getAttribute() to find the string contained within the data-unit attribute and concatenates that to the this.value string.
That should probably be:
show.innerHTML = this.options[this.selectedIndex].value;
If the list is not a dynamically generated one, why don't you use an "if else" construct or a "switch" construct on the populated values and display whatever you like?
Use the value attribute for the value you want submitted to the server since value is meant to contain a string that is meant to be interpreted by a computer as part of a form.
Use a different attribute to associate human readable text with the <option>. title and longdesc would be good choices.
I would recommend using jQuery if you can. If you're expecting to be able to use html5 compliant browsers, you can use the data attributes on your <option> elements. This way you'd be able to store whatever attributes you found useful.
jQuery data attributes usage
You can use .innerHTML instead of .value if you want to display the text from the drop down. If you want something completely different to be displayed, you'll need a lookup table or something similar - might be easier to use jQuery.

Categories

Resources