how to sset the default setting - javascript

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

Related

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";

Element not displayed with obj.style.display='';

I have a strange issue on a HTML page containing a span which won't be displayed:
<span id="wipThankYou">Thank you for submitting your email!</span>
It is initially hidden with the following CSS:
#wipThankYou {
display: none;
}
When a user clicks on a button, the following code is executed:
function T_show(obj) {
if ( obj !== null ) {
obj.style.display='';
}
}
var wipThankYou = document.getElementById("wipThankYou");
T_show(wipThankYou);
I can see the code being executed step-by-step in Chrome, but the span is not displayed. When I inspect the element, its CSS is not changed. I can replicate the issue on JsFiddle.
What am I doing wrong?
UPDATE
I took this code from You Might Not Need JQuery, but apparently, it is faulty. Thanks.
obj.style.display='' resets the inline style of the element. You need to specify how you want to display it if you want it to be shown. Change it to a display value and it will fix it, such as obj.style.display='inline-block'
obj.style.display='inline-block';
or whatever the display you want (inline, block...), but it shouldn't be empty.
See it here: http://jsfiddle.net/shomz/ELmqf/
obj.style.display=''; is not valid for css display as display can be :inline(default), block, inline-block (more values you can find here http://www.w3schools.com/cssref/pr_class_display.asp)
so solution for you to set style to valid value. For example obj.style.display='block';
Live example http://jsfiddle.net/a699x/2/

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

Need function to run on selecting an option in dropdown box

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.

JQuery Select Box and Loop Help

Thanks for reading. I'm a bit new to jQuery, and am trying to make a script I can include in all my websites to solve a problem that always drives me crazy...
The problem:
Select boxes with long options get cut off in Internet Explorer. For example, these select boxes:
http://discoverfire.com/test/select.php
In Firefox they are fine, but in IE, the options are cut off to the width of the select when they drop down.
The solution:
What I am looking to do, is create a script that I can include in any page that will do the following:
Loop through all the selects on the page.
For each select:
A. Loop through its options.
B. Find the width of the longest option.
C. Bind a function to expand the select to that width on focus (or maybe click...).
D. Bind a function to shrink to it's original width on blur.
I've managed to do most of step #2 for one select box.
I found that getting the options width was a problem (especially in IE), so I looped through and copied the text of each option to a span, measured the span width, and used the longest one as the width the select will be expanded to. Perhaps somebody has a better idea.
Here is the code
<script type='text/javascript'>
$(function() {
/*
This function will:
1. Create a data store for the select called ResizeToWidth.
2. Populate it with the width of the longest option, as approximated by span width.
The data store can then be used
*/
// Make a temporary span to hold the text of the options.
$('body').append("<span id='CurrentOptWidth'></span>");
$("#TheSelect option").each(function(i){
// If this is the first time through, zero out ResizeToWidth (or it will end up NaN).
if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) {
$(this).parent().data( 'OriginalWidth', $(this).parent().width() );
$(this).parent().data('ResizeToWidth', 0);
$('CurrentOptWidth').css('font-family', $(this).css('font-family') );
$('CurrentOptWidth').css('font-size', $(this).css('font-size') );
$('CurrentOptWidth').css('font-weight', $(this).css('font-weight') );
}
// Put the text of the current option into the span.
$('#CurrentOptWidth').text( $(this).text() );
// Set ResizeToWidth to the longer of a) the current opt width, or b) itself.
//So it will hold the width of the longest option when we are done
ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') );
// Update parent ResizeToWidth data.
$(this).parent().data('ResizeToWidth', ResizeToWidth)
});
// Remove the temporary span.
$('#CurrentOptWidth').remove();
$('#TheSelect').focus(function(){
$(this).width( $(this).data('ResizeToWidth') );
});
$('#TheSelect').blur(function(){
$(this).width( $(this).data('OriginalWidth') );
});
alert( $('#TheSelect').data('OriginalWidth') );
alert( $('#TheSelect').data('ResizeToWidth') );
});
</script>
and the select:
<select id='TheSelect' style='width:50px;'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
<option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option>
<option value='5'>Five</option>
<option value='6'>Six</option>
<option value='7'>Seven...</option>
</select>
Hopefully this will run for you if you want to run it, or you can see it in action here: http://discoverfire.com/test/select.php.
What I need help with:
This needs a bit of polish, but seems to work ok if you specify the select box.
However, I don't seem to be able to figure out how to apply it to all select boxes on the page with a loop. So far, I have this:
$('select').each(
function(i, select){
// Get the options for the select here... can I use select.each...?
}
);
Also, is there a better way to get the length of the longest option for each select? The span is close, but not very exact. The problem is that IE returns zero for the option widths of the actual selects.
Any ideas are very welcome, both for the questions asked, and any other improvements to my code.
Thanks!!
To modify each select, try this:
$('select').each(function(){
$('option', this).each(function() {
// your normalizing script here
})
});
The second parameter (this) on the second jQuery call scopes the selecter ('option'), so it is essentially 'all option elements within this select'. You can think of that second parameter defaulting to 'document' if it's not supplied.
I was able to replicate your results for all selects on a page in IE7 using this code, which I find much simpler than the span method you are using, but you can replace the "resize" function with whatever code suits your needs.
function resize(selectId, size){
var objSelect = document.getElementById(selectId);
var maxlength = 0;
if(objSelect){
if(size){
objSelect.style.width = size;
} else {
for (var i=0; i< objSelect.options.length; i++){
if (objSelect[i].text.length > maxlength){
maxlength = objSelect[i].text.length;
}
}
objSelect.style.width = maxlength * 9;
}
}
}
$(document).ready(function(){
$("select").focus(function(){
resize($(this).attr("id"));
});
$("select").blur(function(){
resize($(this).attr("id"), 40);
});
});

Categories

Resources