How can I add or remove dropdown items dynamically in jQuery? Below code is not working
$("#dropdownId").remove("<option value='12'>testing</option>");
$("#dropdownId").add("<option value='12'>testing</option>");
Can anyone suggest a way to do this?
To add elements, use .append():
$('#dropdownId').append('<option value="12">testing</option>')
or .appendTo():
$('<option/>', { val: 12, text: 'testing' }).appendTo('#dropdownId');
To remove, use .remove() differently:
$('#dropdownId').find('option').filter(function ()
{
return this.value === '12' && $(this).text() === 'testing';
}).remove();
As a general recommendation, you should really read the API docs for simple jQuery questions like these. If you had read the documentation for .add(), for instance, you'd see that it does not do what you thought.
Use a standard selector for the item you want to remove, rather than passing html markup:
$('#dropdownId option[value="12"]').remove();
// or
$('#dropdownId').remove('option[value="12"]');
(I'm assuming you don't have more than one option with the same value.)
The (approximate) opposite of .remove() is .append():
$("#dropdownId").append("<option value='12'>testing</option>");
Remove:
$("#selectList option[value='2']").remove();
Add:
$('#selectList').append('<option>'+val+'</option>');
Use append instead of add !
add is not writing method.
use append() like,
$("#dropdownId").append("<option value='12'>testing</option>");
here's some information from jQuery API: http://api.jquery.com/append/
Related
I'm trying to only select ARTICLE items that do not have the style attribute set.
I could do this easily with jQuery but I'm using a library that is javascript only, called scrollreveal.
I can easy get items that have the style attribute using this ARTICLE[style].
But I want to reverse this and get items that do not have a style attribute, in the same way using a not equal to != operator on the selector.
I've tried this...
// scroll reveal article
window.sr = new ScrollReveal({ reset: false });
sr.reveal('ARTICLE[!=style]', {
duration: 1000
});
But it's not working as expected, does anyone know if its possible to achieve this using not equal too on a attribute selector?
Thanks in advance for any help on this.
Almost there. The :not pseudoclass should do the trick:
article:not([style])
Just use :not([style]):
const matches = document.querySelectorAll('div:not([style])')
console.log(matches)
<div id="foo" style="width:100px;"></div>
<div id="bar"></div>
<div id="baz"></div>
That is if I'm correct in assuming that sr.reveal uses document.querySelector internally.
I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......
When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....
I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(
Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.
This is exactly I want to achieve FIDDLE
There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:
However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:
<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...
then you can:
$(document).ready(function(){
$('.divbuttons').click(function() {
var div = $(this).data("div");
$('.divs.selected').removeClass('selected');
$('#' + div).addClass('selected');
});
});
This is an easy one. There is no document.getElementByClass
You have document.getElementById or document.getElementByClassName
There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.
try
$(document).ready(function () {
$("button[class^=div]").click(function () {
$(".divs.selected").removeClass("selected");
$("#" + $(this).attr("class")).addClass("selected");
});
});
DEMO
I want to create a simple custom tooltip plugin for jQuery that for every element that has a data-custom-tooltipset. So, something like :
Hhahaha
OR
<button data-custom-tooltip="This is my tooltip for the button Tex">Haha Button :) </button >
So, the function to display the tooltip would be triggered only if the data-custom-tooltip is NOT empty.
Close enough to this : jQuery selectors on custom data attributes using HTML5
You can use :not() selector and remove the empty ones
$('[data-custom-tooltip]:not([data-custom-tooltip=""])')
or
$('[data-custom-tooltip]').not('[data-custom-tooltip=""]')
or based on what #VisioN said in the comments with the Not Equal Selector
var xxx = $('[data-custom-tooltip][data-custom-tooltip!=""]');
use like this
$("[data-custom-tooltip]:not([data-custom-tooltip='']").click(function(){alert("clicked");});
fiddle
Try
.filter()
var tooltip_el = $('[data-custom-tooltip]').filter(function () {
return $.trim($(this).data('custom-tooltip')) != '';
});
I'm new in Jquery, and I have this code:
jQuery(document).ready(function(){
var title = jQuery(".fullVisaImg").attr("inselect");
var links = jQuery(".ff_elem>option");
for(var i=0; i<links.length; i++) {
if (title == links[i].value) {
links[i].attr("selected", "selected"); // here is my problem
alert(links[i].value);
return;
}
}
});
i have a select element on my pages, and want to make one of elements selected. if I comment line with // here... all works good, and i see all my option values.
Thanks for help!
When you use [] to access an element in a jquery set, you get back the raw DOM element. So you can not use jquery methods on it directly..
You should also use .prop instead of .attr() when interacting with properties of the element
So use
links.eq(i).prop("selected", true);
replace you for loop with:
jQuery(".ff_elem").val(title);
I have created this DEMO for you. Check it out.
Although You can iterate through all your option elements and find your option element, and then do this:
links[i].prop("selected", true);
but there is no need to iterate when you can simply let your select element do this for you as I have mentioned above.
This is actually how you can select an option based on the value your options have.
$('select').val('value of the option you want to select');
so use
$(".ff_elem").val(title);
Following your code, you could use:
links.eq(i).prop("selected", true);
if your jquery version is above 1.6+ then use this
links.eq(i).prop("selected", true);
else
links.eq(i).attr("selected", "selected");
It can be much simpler. Try something like this:
jQuery(document).ready(function(){
var title = jQuery(".fullVisaImg").attr("inselect");
jQuery(".ff_elem>option[value=" + title + "]").attr("selected", "selected");
});
links is a jQuery collection. When you loop through it, you're just getting the raw element, not a jQuery wrapped version, so you can't use .attr().
Use this instead at your problem line.
$(links[i]).attr("selected", "selected");
I have this line of code:
$('#sitesAccordion .groupOfSites').click(function() {
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
console.log(lastOpenSite);
});
I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:
.hasClass(':not(.closedTab)');
What is the problem?
My purpose is to create my own accordion (without using jQuery UI)
and I am trying to write it like this:
$('#sitesAccordion .groupOfSites').click(function() {
//Get the last opened tab
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
//Close last opened tab and add class
lastOpenSite.hide().toggleClass('closedTab');
//Open the current Tab
$(this).children('.accordionContent').toggle('fast');
// remove class from open tab
$(this).toggleClass('closedTab');
});
Is this the best way?
thanks,
Alon
Use the not function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.
It's much easier to do like this:
if(!$('#foo').hasClass('bar')) {
...
}
The ! in front of the criteria means false, works in most programming languages.
jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
You can also use jQuery - is(selector) Method:
var lastOpenSite = $(this).siblings().is(':not(.closedTab)');
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');