remove items from HTML dropdownList at checkbox un-check event - javascript

I have a list of check-boxes and a drop-down list.I managed to add elements dynamically to dropdown list when I check the checkboxes.
How can I remove corresponding Items dynamically from drop-down list when I un-check particular checkbox.
Here is my code
//<input type="checkbox" name="docCkBox" value="${document.documentName}" onclick="handleChange(this)"/>
// check box onclick event will call this function
function handleChange(cb) {
if (cb.checked)
{
// Create an Option object
var opt = document.createElement("option");
// Add an Option object to Drop Down/List Box
document.getElementById("query_doc").options.add(opt);
// Assign text and value to Option object
opt.text = cb.value;
opt.value = cb.value;
}
else{
//I want to remove a particuler Item when I uncheck the check-box
//by below method it will always remove the first element of the dropdown but not the corresponding element
var opt = document.createElement("option");
opt.text = cb.value;
opt.value = cb.value;
document.getElementById("query_doc").remove(opt);
}
}

You need to get access to the option that is already in the select tag, not create a new one. I would do this by getting all of the options then checking each one to see if it has the value of the checkbox. The code would look something like this inside the else block:
var opts = document.getElementById("query_doc").getElementsByTagName('option');
for(var i = 0; i < opts.length; i++){
if(opts[i].value == cb.value){
opts[i].parentNode.removeChild(opts[i]);
}
}
I haven't tested the code, but the general idea is there.

You will have to find the index of the desired option and remove it by index.

Related

jQuery Chose plugin how to remove selected item from drop down

I im using jquery choose plugin that is using two input boxes when page loads...and a need like in this example when i select number 1 in first box that this number is removed from second input box....this works fine...but problem is when i add dynamically input box i can't get item number 1 removed from added dynamic input box.
So question is: how can i remove selected values from input box when selecting other input boxes that is added dynamically and selected items in each select box is not visible in all selected box that exists and is added dynamically?
Here is jsfiddle:
[http://jsfiddle.net/dq97z/640/][1]
And here is picture what i need:
Maybe this will help you out
http://jsfiddle.net/s9r73qjm/
//an array to save selections
var selectedVals = [];
//push to the array when we have selected
selectedVals.push(selectedValue);
//check on the values when building the drop down
$( "#btn_newrow" ).click(function() {
var newList = document.createElement("select");
newList.dataset.placeholder = "Number row 3";
newList.style.width = "350px";
var newListData = new Option("placeholder", "placeholder");
for (var i = 0; i < 6; i++){
if (selectedVals.indexOf(i.toString()) == -1){
//then it hasn't been selected
newListData = new Option(i.toString(), i.toString());
newList.appendChild(newListData);
}
$( ".wrapper" ).append(newList);
}
});

Add items to listbox using javascript

I am trying to add few items to a list box from a text box using javascript. but the problem is as soon as I am adding the items, it gets visible in the list box for a second and then gets deleted. Any solution for this?
I am adding items from TextBox4 to ListBox1
function AddToList() {
// Create an Option object
var opt = document.createElement("option");
// Add an Option object to List Box
document.getElementById("ListBox1").options.add(opt);
opt.text = document.getElementById("TextBox4").value;
opt.value = document.getElementById("TextBox4").value;
document.getElementById("ListBox1").options.add(opt);
}
document.getElementById("ListBox1").options.add(opt); // remove this line
opt.text = document.getElementById("TextBox4").value;
opt.value = document.getElementById("TextBox4").value;
document.getElementById("ListBox1").options.add(opt);
As you're appending an <option> which has no value or text.
Got the solution, Need to add
return false;
at the end of the function.

Jquery mobile interfering with javascript filling select box

I am trying to fill an html select box programmatically using javascript. I have found that although my code is working, jquery mobile is interfering with what displays in the select box. I am setting the selected option, which is working, but the value displayed in the select box is the wrong value. It isn't changing from what I had it originally filled as from the html.
I am linking in: "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css". Is there anyway to get around the jquery? I can't just remove the jquery css. That would break everything on my site, and I don't have time to redo it all.
Here is a jsfiddle of the problem: http://jsfiddle.net/RjXRB/1/
Here is the my code for reference:
Here is my javascript function that fills the select box:
function printCartList(newCart){
// newCart is an optional parameter. Check to see if it is given.
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// Create a cart list from the stored cookie if it exists, otherwise create a new one.
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select box
var select = document.getElementById("select_cart");
// Get the number of options in the select box.
var length = select.options.length;
// Remove all of the options in the select box.
while(select.options.length > 0){
select.remove(0);
}
// If there is a new cart, add it to the cart.
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Populate the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value && newCart != "a_new_cart_was_not_provided_12345abcde"){
// Set the selected value
alert(carts.option[i].value);
opt.selected = true;
// I tried changing the value of a p tag inside the default option, but that didn't work
document.getElementById("selectHTML").innerHTML = carts.option[i].html;
}
if(opt.value == "dd"){alert("hi");};
select.appendChild(opt);
}
}
Here is my html:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890"><p id="selectHTML">*** New Cart ***</p></option>
</select>
</form>
Any help would be greatly appreciated.
I know this question is about a month old, but I stumbled upon it because I was having the exact same issue. I eventually fixed it by doing this:
After programmatically setting the value, I manually fired the change event on that select box. I guess it forced jQuery mobile to update all of it's enhanced markup related to that element. Slightly annoying, but fortunately very easy to work around.
$("#country").val("US");
$("#country").change();
Hope that helps somebody.

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});

to see if item in dropdownList has been selected

I would like to know what the best way would be to loop through a dropdown list in html to see if and item has been selected or not.
I know in C# it would be something along the lines of
int selected = cmbFamily.SelectedIndex;
for (int loop = 0; loop < cmbFamily.Items.Count; loop++)
{
if (selected == -1)
{
MessageBox.Show("please select an item", "Please", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
how would I go about in doing this with javascript?
<tr style="font-size:12pt; font-weight:bold; color:#FFFFFF; font-family:High Tower Text;">
<td>Family to join:</td>
<td><select name="drpFamily">
<option/>-select-
<option/>Gambino
<option/>Genovese
<option/>Lucchese
<option/>Colombo
<option/>Bonanno
</select><font color="red">*</font></td>
</tr>
Kind regards
Arian
First off you HTML code is totally wrong. It is not </option>text, it is <option>text</option>
To loop through the options it is as simple as
//var options = document.getElementById("selectId").options;
var options = document.formName.selectName.options;
for(var i=0;i<options.length;i++){
if(options[i].selected){
alert(options[i].value);
}
}
but there is no need to loop through a single select. The easiest way is just to use selected index for a single select.
//var sel = document.getElementById("selectId");
var sel = document.formName.selectName;
var opt = sel.options[sel.selectedIndex];
alert(opt.value);
First: your HTML is wrong.
It should be
<option>-select-
...
or
<option>-select-</option>
...
If you just want the selected value, you can get it via the value attribute of the select element:
var value = document.getElementsByName('drpFamily')[0].value
This only works if there is only one element with name drpFamily. If not, you have to find an appropriate way to select it.
You might want to compare it against the first value (which is selected by default)
if(value !== '-select-')
You could also add a change event listener to the select element:
document.getElementsByName('drpFamily')[0].onchange = function() {
if(this.value !== '-select-') {
//a value other '-select-' than was selected
}
}

Categories