Delete specific range of elements JQuery - javascript

Html:
<select id ="combooptions">
<option id="combostart" value=""></option>
</select>
js:
var str = "";
if (combonews.length > 0)
for (var i in combonews) {
str += "<option value='" + combonews[i][0] + "'>" + combonews[i][1] + "</option>";
}
jQuery("#combooptions").append(str);
It works fine, but now I want to remove those appended one, leaving the initial 1 option tag, as shown above.
I tried:
jQuery("#combooptions").html('');
//or
jQuery("#combooptions").append('');
//or
jQuery("#combostart").append('');
//or
jQuery("#combostart").html('');
but no success.
Please help
thank You

Since you gave the first option a unique ID, just do:
$('#combostart ~ option').remove();
What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

To shrink a select list, you can also lower the number of options:
document.getElementById("combooptions").length = 1;
With jQuery:
$("#combooptions")[0].length = 1;
More generic idea to remove "all but the first":
$("#combooptions :not(:first-child)").remove();
Example: http://jsfiddle.net/kVRpy/

You could select all options and then remove the one with id combostart from your selection.
Then call .remove() to remove the unwanted options.
$('#combooptions option').not('#combostart').remove();

Try this:
$('#combooptions').html("<option id='combostart' value=''></option>");

Related

on change selects not working well

I`m trying to make a simple select which generate the next select box...
but I cant seem to make it work
so, as you can see I'm making divs that have ID and parent, when I'm clicking on the first select the value generate the next select box with the divs and the parent value.
this is the jQuery, but for some reason I cant understand why its not working.
$(document).ready(function() {
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
i++;
t = '#ss' + i;
var pick = $(this).val();
$('#picks div').each(function() {
if ($(this).attr('parent') == pick) {
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');
}
$('#ss' + i).removeAttr('disabled');
})
console.log(t);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='picks'>
<div id='29' parent='26'>Pick1</div>
<div id='30' parent='29'>Pick11</div>
<div id='31' parent='26'>Pick</div>
</div>
<select id="ss1">
<option >First pick</option>
<option value="26">Angri</option>
<option value="27">lands</option>
<option value="28">tree</option>
</select>
<select id="ss2" disabled>
<option >Secound Pick</option>
</select>
<select id="ss3" disabled>
<option>Third Pick</option>
</select>
Here is a jsfiddle jsfiddle
Is this what you were shooting for? https://jsfiddle.net/6c5t8ort/
A couple things,
var t = '#ss' + i;
$(t).change(function() {
This only adds the change event to the first dropdown. If you give jQuery a selector (a class) if will add the event to all the elements though. Also the way you had your i variable set up means it would increment on every change.
The code below only attaches a change listener to the first ss ss1 so the change function is never called when you change ss2.
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
You can fix this by adding a class on each select and using $(".myClass").change(function() {
or you can just attach the listener to all selects $("select").change(function() {
Also the value for the option tag does not include a "parent" number. In this case it would be Pick, Pick1, or Pick11.
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');

Dynamically adding element to Select and setting the selectindex in JQuery

I've created a dynamic select list box as below
for (var i in c) {
//alert(c[i].IsDefault);
if(c[i].IsDefault==true){
//alert('found default');
$("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
temp = c[i].Code;
}
else{
$("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
}
}
refreshed it
$('#AnsType').selectmenu('refresh');
I tried all these methods and tried to select teh 2nd element in teh listnone worked for me.
$('#AnsType').val(temp.toString());
$('#AnsType').get(3).selectedIndex = 3;
$('select#AnsType').val('3');
$("#AnsType option[text='3']").attr("selected","selected") ;
$("#mydropdownlist").attr('selectedIndex', 1);
$('#AnsType').val(3);
$("#AnsType").attr('selectedIndex', 2);
$("#AnsType").val(c[parseInt(temp)].Code);
$("select#AnsType option[selected]").removeAttr("selected");
$("select#AnsType option[value='"+temp+"']").attr("selected", "selected");
this is how when my listbox is created
<select id="AnsType" name="AnsType">
<option value="1">Obokad</option>
<option value="3">Egen bokning</option>
</select>
Any help is appreciated and thanks in advance for your help..
If you want some element to be pre-selected when creating the menu, add the selected attribute to the corresponding option element:
if(c[i].IsDefault==true){
$("#AnsType")
.append("<option value='" + c[i].ID + " selected='selected'">" + c[i].Code+ "</option>");
temp = c[i].Code;
}
Note that you have to refresh again the selectmenu after you programmatically change the value of the underlying select element:
$('#AnsType').val('3');
$('#AnsType').selectmenu('refresh');
Documentation
refresh update the custom select
This is used to update the custom select to reflect the native select element's value. If the number of options in the select are different than the number of items in the custom menu, it'll rebuild the custom menu. Also, if you pass a true argument you can force the rebuild to happen

Using jQuery to determine an element's class

Most examples I can find showing how to work with attributes show how to set them and not how to retrieve them. In my case, I am trying to get the class of an and then parse it to determine its parent value.
HTML:
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
For any given option from the child list, I need to look at the class attribute, parse the name looking for the number (“sub_[n]”) and then grab the value of the option in the parent list.
My code so far (childVal has a value of “5” in my test case):
var class = child.find("option[value=" + childVal + "]").attr("class");
The above class variable is coming back “undefined.” I know the .find is working because I can use it for other things. The problem is getting at the class name.
Once I get the class name, I can strip out the “sub_” to get at the id number.
Is there a better way to do this? Why is .attr(“class”) returning undefined?
Here's a Fiddle link http://jsfiddle.net/n6dZp/8/ to a broken example.
Thank you,
Rick
This is the full function I am working on. It's a cascading select list.
<script type="text/javascript">
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
var className = child.find("option[value=" + childVal + "]").attr("class");
** need code here to select the parent and the child options based
on childVal **
}
}
$(function () {
$('.categoryform').find('.child').change(function () {
if ($(this).val() != null) {
$('.categoryform').find('#CategoryId').val($(this).val());
}
});
});
$(function () {
cascadeForm = $('.categoryform');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, "5");
});
</script>
class is a reserved word in Javascript, so you can't have a variable with that name. Try
var className = child.find("option[value=" + childVal + "]").attr("class");
Don't use class as a variable name. Kills IE.
This will work but what is child variable equal to?
To obtain the class attribute:
var classAttribute = $('#child').find('option[value="' + childVal + '"]:first').attr('class');
To obtain the 'n' value you can parse the class attribute with a RegEx:
var nValue = /\bsub_([\S]*)\b/.exec( classAttribute )[1];
Hope it helps you.
My apologies, I didn't read your question very carefully at first. Here's my take on what you should do:
var parentVal = $('.child option[value=' + childVal + ']').attr('class').substr(4);
OLD ANSWER
This should do the trick for you:
$(function() {
$('#child').change(function() { $('.parent').val($(this).children(':selected').attr('class').substr(4));
});
});
Here's a live demo: http://jsfiddle.net/n6dZp/
For a start you are missing the $
You need:
var class = $(".child").find("option[value=" + childVal + "]").attr("class");

Iterate over the options in a HTML select with jQuery

I got this example from a blog, but every time I do this:
$(':input[name=' + inputName + ']').each(function(i, selected)
{
alert($(selected).text());
});
I got all an alert with all the options together :(
I have to search by the input name always, the inputs have no id.
Which is the right way to do it?
Kind regards.
That's because select tag is found by jquery, not option tags
This will give you list of the options.
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
An example
Assuming your HTML is similar to this
<SELECT NAME="mylist">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</SELECT>
you need to modify your selector to iterate over the <OPTION> tags, your selector was iterating over the <SELECT> tag
var inputName = mylist;
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
Without seeing your html, try this:
$(":input[name='" + inputName + "'] option").each(function(i, selected) {
alert($(selected).text());
});

How do you remove all the options of a select box and then add one option and select it with jQuery?

Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id="mySelect" size="9"> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution..
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
why not just use plain javascript?
document.getElementById("selectID").options.length = 0;
If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:
$('#mySelect').find('option:not(:first)').remove();
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.
$(function() {
$('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
$("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
// Bind click event to each radio button.
$("input[name='myRadio']").bind("click",
function() {
switch(this.value) {
case "1":
$('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
break ;
case "2":
$('#mySelect').find('option').remove() ;
var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
var options = '' ;
for (var i = 0; i < items.length; i++) {
if (i==0) {
options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
}
else {
options += '<option value="' + items[i] + '">' + items[i] + '</option>';
}
}
$('#mySelect').html(options); // Populate select box with array
break ;
} // Switch end
} // Bind function end
); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input name="myRadio" type="radio" value="1" /></label>
<label>Two<input name="myRadio" type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.
var ClearOptionsFast = function(id) {
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
More info here.
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
The first line of code will remove all the options of a select box as no option find criteria has been mentioned.
The second line of code will add the Option with the specified value("testValue") and Text("TestText").
Building on mauretto's answer, this is a little easier to read and understand:
$('#mySelect').find('option').not(':first').remove();
To remove all the options except one with a specific value, you can use this:
$('#mySelect').find('option').not('[value=123]').remove();
This would be better if the option to be added was already there.
How about just changing the html to new data.
$('#mySelect').html('<option value="whatever">text</option>');
Another example:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
First clear all exisiting option execpt the first one(--Select--)
Append new option values using loop one by one
$('#ddlCustomer').find('option:not(:first)').remove();
for (var i = 0; i < oResult.length; i++) {
$("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
}
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
I saw this code in Select2 -
Clearing Selections
$('#mySelect').val(null).trigger('change');
This code works well with jQuery even without Select2
Cleaner give me Like it
let data= []
let inp = $('#mySelect')
inp.empty()
data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))
save the option values to be appended in an object
clear existing options in the select tag
iterate the list object and append the contents to the intended select tag
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};
$('#selectID').empty();
$.each(listToAppend, function(val, text) {
$('#selectID').append( new Option(text,val) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I used vanilla javascript
let select = document.getElementById("mySelect");
select.innerHTML = "";
Hope it will work
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
The shortest answer:
$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
Try
$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");
OR
$('#mySelect').html('<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);

Categories