jQuery display none a option in a form - javascript

I want to display none a option of a form.
HTML:
<option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
jQuery:
if(jQuery('option').attr('value') == 'top-10-villen-de'){
jQuery(this).css('display', 'none');
}
I've a issue in my if statement but I can't figure out where is my issue.
Can somebody helps me?
Thank you.

Hiding the dropdown option isn't compatible with all browser.
I've got a better option.
wrap the option into span and when you need it back unwrap it
Fiddle link : http://jsfiddle.net/xms2uydx/

You are using wrong this see this example for THIS Scope
http://jsfiddle.net/kevalbhatt18/r2m2ucgv/2/
The above example is give you difference between two this.
1. which is out of Jquery.
2. which is inside jquery function.
so as you can see in example first console i.e console.log(this) will return window object.
2 . $(this) which is inside click function will give you different value it is related to your button it will gives you button scope
you can also use
jQuery('option').find('.level-0').css('display', 'none')
if you know the class of option.
HTML
<button>option 1</button>
<button>option 2</button>
<select>
<option class="level-0" value="top-10-villen-de">Top-10-Villen</option>
<option class="level-1" value="top-1">Top-20</option>
</select>
Jquery
console.log(this)
$('button').click(function () {
if ($(this).text() === "option 1") {
if (jQuery('option').attr('value') == 'top-10-villen-de') {
console.log('inside')
console.log(jQuery('option[class="level-0"]'))
jQuery('option[class="level-0"]').css('display', 'none');
}
} else {
jQuery('option[class="level-0"]').toggle()
}
})

That is because context this in if statement do not refer to option element.Correct way to achieve this would be to find element with attribute value equal to top-10-villen-de along with .hide():
jQuery('option[value="top-10-villen-de"]').hide();
FYI, the hiding of option elements do not work. a good workaround for this would be to disable the option by setting its disabled property to true.

In jQuery , whenever you have more than one element in DOM , then to access all elements you have to use $('selector').each(function(index,Obj){}).
Use this code to hide the options you want
$('#temp').find('option').each(function(index,Obj){
if($(this).attr('value')=='2')
$(this).css('display', 'none');
})
Demo

You can set display none when it the value is top-10-villen-de
jQuery( "select" ).change(function() {
if(jQuery(this).val() == 'top-10-villen-de'){
jQuery(this).find("option[value='top-10-villen-de']").css('display', 'none');
}
});
Here the fiddle
https://jsfiddle.net/jva8ju1s/

Related

Why does jQuery change event not work with select option?

The following code should enable the second select element (id=ANSWER.TTQ.MENSYS.8.) when the value in the first select element (id=ANSWER.TTQ.MENSYS.9.) changes, but it doesn't work and I've exhausted all the options I can think of, including those suggested already on this site. (NOTE: the element ids must be these values, hence I'm not using # to select them, as that doesn't work).
$(document).ready(function() {
$("input[id='ANSWER.TTQ.MENSYS.9.']").bind('change',function() {
alert ('this script runs');
$("input[id='ANSWER.TTQ.MENSYS.8.']").removeAttr('disabled');
});
});
If I substitute the enabled select (id=ANSWER.TTQ.MENSYS.9.) with a button and the change event with a click event; it works. So why not with change event on the select element?
Thank you for your help.
Firstly, you can select by id using the # character. Secondly you need to escape the . in the id attribute otherwise the selector engine will look for an element with the id ANSWER which also has TTQ, MENSYS and 9 as classes. Try this:
$("#ANSWER\\.TTQ\\.MENSYS\\.9\\.").bind('change', function () {
alert('this script runs');
$("#ANSWER\\.TTQ\\.MENSYS\\.8\\.").removeAttr('disabled');
});
Example fiddle
$(document).ready(function() {
$("#ANSWER.TTQ.MENSYS.9.").bind('change',function() {
alert ('this script runs');
$("#ANSWER.TTQ.MENSYS.8.").removeAttr('disabled');
});
});
select is not input( i.e. text input)

How to use string argument of a function in a jQuery expression

I have some set of links and select boxes. My html code is below:
<div>
<div>
<a href='#' onclick='set_checked(false,"checkbox1")'>clear</a>
<a href='#' onclick='set_checked(true,"checkbox1")'>select</a>
</div>
<div>
<input type='checkbox' name='checkbox1'/>
</div>
</div>
<div>
<div>
<a href='#' onclick='set_checked(false,"checkbox2")'>clear</a>
<a href='#' onclick='set_checked(true,"checkbox2")'>select</a>
</div>
<div>
<input type='checkbox' name='checkbox2'/>
</div>
</div>
Now my requirement is when I click on select link I have to check the checkbox based on it's arguments, and reversal for clear. Here I'm passing two parameters. One is to pass Boolean value (i.e. if true check else uncheck) and another one is to pass name argument of a checkbox field. And I'm using the following function to check or uncheck a checkbox:
function set_checked(checked,inputFeildName){
$('input[name=inputFeildName]').attr('checked',checked);
}
but the above code is not working. And this is my fiddle http://jsfiddle.net/vu6fs/5/.
I have one more requirement, before selecting any checkbox all clear links have to be disabled, after selection of checkbox respective clear link have to be enable. I'm applying opacity and also 'disabled' property in JavaScript but it's not working,can anyone suggest me where my fault is.. Can anyone please help me?
jQuery 1.6+
function set_checked(checked,inputFeildName){
$('input[name="'+ inputFeildName +'"]').prop('checked',true);
}
jQuery 1.5 and below
function set_checked(checked,inputFeildName){
$('input[name="'+ inputFeildName +'"]').attr('checked','checked');
}
Here is an example for your extension of question (more you want, About disable/enable a tag on checkbox change)
CSS
.disButton {
background: transparent;
border: none;
}
.disButton a {
text-decoration: none;
color: #ddd;
}
jQuery
$('input:checkbox').on('change', function() {
enable_clear(this, this.checked);
}).change();
function enable_clear(el, checked) {
var target = $(el).parent('div').prev('div').find('a:contains(clear)');
if (checked) {
target.unwrap();
} else {
target.wrap($('<button/>', {
disabled: true,
'class': 'disButton',
width: target.width() + 'px'
}));
}
}
$('a').on('click', function(e) {
e.preventDefault();
var target = $(this).parent().next('div').find('input:checkbox');
if (!target.is(':checked') && $(this).text() == 'select') target.click();
if ($(this).text() == 'clear') target.click();
});
DEMO
I think this is what you are trying to do... btw you have misspelt field so be careful when using the variable/attr again.
function set_checked(checked,inputFeildName){
$('input[name="'+inputFeildName+'"]').attr('checked',checked);
}
you forget to append string that i did as below , this will resolve your issue
function set_checked(checked,inputFeildName)
{
$('input[name="'+ inputFeildName+'"]').attr('checked',checked);
}
There are some errors in your fiddle:
Your function set_checked is declared in the onLoad-Handler (as selected), and is only available in that locally and not in the global scope. Remove the wrapping function by selecting "no wrap (head)" or assign your function to window.set_checked.
Please note that the checked attribute only represents the default value of the checkbox, to change the actual state you need to use the checked property (with jQuery, you can use val()).
If you wanted to change the default value, you can't do it by setting the attribute to (the string) false. The attribute represents a checked checbox through its existence, you would need to use removeAttribute() for disabling. It's easier to use the defaultChecked property with a boolean value.
last but not least there's the obvious error detected by all others: To use a variable, you will need to use it instead of putting its name into a string (like in PHP).
You also might be more happy with ids than name attributes. I've updated your fiddle with a proper solution: http://jsfiddle.net/vu6fs/7/
To disable the clear/select link when it's not appropriate:
you can't disable a link (anchor) as you can a form element (see Disable link using javascript, jQuery disable a link, Disable link using css). OK, we don't really need to disable its functionality (nothing changes), so so I guess you only think of graying it out. This can be done with CSS, and you'll need to trigger the update both on user-change events and the setting through set_checked. Example code at http://jsfiddle.net/vu6fs/9/
It might be easier to use just one link that toggles the checked state. Its lettering may change between "clear" and "select", depending on the current state.
I now have written a plugin (i.e. a jQuery prototype function) to add those links dynamically to any checkbox elements. That means it also can use (scoped) click handlers instead of a global-scope-polluting set_checked function.
The function has a little error:
function set_checked(checked,inputFeildName){
$(**'input[name='+inputFeildName+']'**).attr('checked',checked);
}

How to get the value of a select box element by its option in javascript?

My select box is as follows:
<select id='list'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
</select>
I want to get the value of option - B without selecting it.
With jQuery I can do the opposite i.e get the text when I know the value through following:
$("#list option[value='2']").text();
But I want the reverse. I tried with following but not working:
$("#owner option['B']").val();
How can I do this?
Use the :contains selector.
Assuming "owner" really is the ID of your <select> (it's "list" in your example), you can use:
$("#owner option:contains('B')").val() // 2
You can use the :contains(text) selector, to only get the elements that contain certain text:
$("#list option:contains('B')").val();
You can use .filter to get the right option element:
$("#list option").filter(function() {
return $(this).text() == "B";
}).val();
http://jsfiddle.net/JWjKf/
try this
var b = $("#list").find('option:contains("B")').val();
see here : http://jsfiddle.net/MxpTZ/1/
Try this script
$('#list option:contains("B")').prop('value') //jquery 1.6 or later
oR
$('#list option:contains("B")').attr('value');
If you wanted to get the element by position, you can do this:
$('#list').children().eq(1).val();

Using .hide() and .show() in jQuery

In my program I have several very similar drop-down menus all with the same name (foo in the following example). On change they hide or show a nearby div tag depending on whether or not "ON" was selected.
$('.togClass').hide();
$('[name*="foo"]').change(function(){
if ($('[value="ON"]').is(':selected')) {
$('.togClass').show('blind', 1000);
} else {
$('.togClass').hide(1000);
}
});
As it is, all of the div tags with class "togClass" toggle when any of the drop down menus choose "ON", is there a way that I can choose to show/hide only the nearby div to the drop-down that chooses "ON"(they are nested in the same div)? I don't want to write a copy of this function for every div I want to hide.
Here is how it works in the HTML:
<select name="foo">
<option value="OFF">OFF</option>
<option value="ON">ON</option>
</select><br/>
<div class="togClass">
//Stuff
</div>
Ofcourse you can. Check out the jquery doc about traversing: http://api.jquery.com/category/traversing/ It has a lot of great examples.
For your problem the solution could be: .closest()
$('div.togClass').hide();
$('select[name*="foo"]').change(function(){
if ($(this).val() == "ON") {
$(this).siblings('div.togClass').show('blind', 1000);
} else {
$(this).siblings('div.togClass').hide(1000);
}
});
You have to tell us a bit more about what "nearby" means. But it appears that the fundamental piece you're missing is the use of $(this) within the change function. Instead of identifying any .togClass item, you want to identify a specific one relative to $(this) -- the element being changed.
Here's one way to do it with the assumption that the associated .togClass div is the next one to be found in the DOM.
$('[name*="foo"]').change(function(){
if( $(this).is(':selected') ) { // relative to the selected item
$(this).next('.togClass').show('blind',1000);
} else {
$(this).next('.togClass').hide(1000);
}
});
Where you see .next() you'll actually need the appropriate jQuery traversal methods -- unlikely to be the one I've randomly assumed in the example.
How about using .closest()?
Should do the trick.

Set the default value in dropdownlist using jQuery

I have many options in my dropdownlist like:
<option value="1">it's me</option>
I need to select the option who have value it's me inside the tag, not by attribute like 1.
How can I do this using jQuery?
if your wanting to use jQuery for this, try the following code.
$('select option[value="1"]').attr("selected",true);
Updated:
Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.
Here below is the updated code.
$('select option:contains("it\'s me")').prop('selected',true);
You need to use the :contains(text) selector to find via the containing text.
Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.
A working example on JSFiddle
You can just do this:
$('#myCombobox').val(1)
val() should handle both cases
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
$('#userZipFiles option').prop('selected', function() {
return this.defaultSelected;
});
$("#dropdownList option[text='it\'s me']").attr("selected","selected");
jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");
One line of jQuery does it all!
$("#myCombobox option[text='it\'s me']").attr("selected","selected");
This is working fine:
$('#country').val($("#country option:contains('It\'s Me')").val());

Categories

Resources