So, I have a situation that I have ran into. The code below just dies when trying to remove something with a hyphen in it. I cannot find anyone else having this issue...
Has anyone else ran into this? What do you do as a work-a-round?
<!DOCTYPE html>
<html>
<body>
<form>
Select a fruit:
<br>
<select id="mySelect" size="4">
<option>Apple</option>
<option>Not-Happening</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>
<button onclick="myFunction()">Remove selected fruit</button>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
for(i = 0; i < x.length; i++)
{
alert(x.length);
x.remove(i);
}
}
</script>
</body>
</html>
And the code below...
$(".mySelect").find("option").each(function(index, el){
var $el = $(el);
var value != '' $el.attr("value");
if (value === "" || value === undefined)
$el.remove();
});
It's not the hyphen, it's just that you're doing this:
for(i = 0; i < x.length; i++)
{
alert(x.length);
x.remove(i);
}
When you remove the option at index 0, all the others move up, but your i variable moves to 1. So the option was at index 1 is now at index 0 and doesn't get removed.
If you want to remove them all, either count backward, or assign to length:
x.length = 0;
If you just want to remove selected ones, work backward:
function myFunction() {
var x = document.getElementById("mySelect");
var i;
for (var i = x.length - 1; i >= 0; --i) {
if (x[i].selected) {
x[i].remove();
}
}
}
Example:
function myFunction() {
var x = document.getElementById("mySelect");
var i;
for (var i = x.length - 1; i >= 0; --i) {
if (x[i].selected) {
x[i].remove();
}
}
}
Select some before clicking the button.
<form>
Select a fruit:
<br>
<select id="mySelect" size="4">
<option>Apple</option>
<option>Not-Happening</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>
<button onclick="myFunction()">Remove selected fruit</button>
With jQuery, it's simpler because jQuery is set-based and you can just remove them all at once:
$("#mySelect option:selected").remove();
Example:
function myFunction() {
$("#mySelect option:selected").remove();
}
Select some before clicking the button.
<form>
Select a fruit:
<br>
<select id="mySelect" size="4">
<option>Apple</option>
<option>Not-Happening</option>
<option>Banana</option>
<option>Orange</option>
</select>
</form>
<br>
<button onclick="myFunction()">Remove selected fruit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I'm developing a decision tree drop-down wherein the selection may change based on the user's decision.
I was able to display the correct results using a loop with the help of selectedIndex if no changes of selection is made but when I change it to other selection that's the time I get an issue
I already tried clearing the stored array by doing this result = [] also this result = 0 but after that it wont recapture the selected dropdown even though I created a separate button for displaying result and clearing result.
Sample Scenario:
I choose A on question 1 then A-1 on question 2 when I click on Display result it will display the correct selection. The issue happens when I change my selection into B on question 1 and B-1 on question 2 because the result still includes the previous selection which is A-1 value even though I created a clear button which clear out the value of the array. The correct answer on that should be B-Value and B-1-Value only.
//THIS IS THE CODE TO CLEAR THE RESULT
function clearResult() {
var result = []
for (var x = 0; x < inputs.length; x++) {
if (inputs[x].selectedIndex > 0) {
inputs[x] = 0;
document.getElementById("demo").innerHTML = '';
}
}
return console.log(inputs);
}
//THIS IS THE CODE TO DISPLAY THE RESULT
var inputs = form1.elements;
function displayResult() {
var result = [];
for (var x = 0; x < inputs.length; x++) {
if (inputs[x].selectedIndex) {
result += inputs[x].value + "</br>";
document.getElementById("demo").innerHTML = result;
}
}
return false;
}
//PLEASE IGNORE THE CODE BELOW
//FOR HIDING DROPDOWN
var base = {
productFilterSetup: function() {
$('.productFilter').each(
function() {
var tmp = new base.filterGroup(this);
tmp.setup();
});
},
filterGroup: function(filter_group) {
var me = this;
me.target_element = filter_group;
me.active_element_index = 0;
me.setup = function() {
$(filter_group).find('option[type=dropdown]').bind('click', function() {
me.update(this);
});
};
me.update = function(target_dropdown) {
var div = $(me.target_element).find('div'),
len = div.length,
i = 0,
j = 0,
dropdowns,
dropdowns_len,
options = [],
options_buffer = '',
num_of_steps = 0;
for (i = 1; i <= num_of_steps + 1; i += 1) {
if ($('div.step' + i).length > 0) {
num_of_steps += 1;
}
}
for (i = 0; i < num_of_steps; i += 1) {
if ($(target_dropdown).parents('div.step' + (i + 1)).length > 0) {
for (j = i; j < num_of_steps; j += 1) {
$('div.step' + (j + 2) + ' option[type=dropdown]').attr('checked', false);
}
}
}
for (i = 0; i < len; i += 1) {
dropdowns = $(div[i]).find('option[type=dropdown]');
dropdowns_len = dropdowns.length;
for (j = 0; j < dropdowns_len; j += 1) {
if ($(dropdowns[j]).is(':checked')) {
options.push(j + 1);
}
}
}
div.addClass('hide');
$('div.option0').removeClass('hide');
for (i = 0; i < options.length; i += 1) {
options_buffer += options[i];
$('div.option' + options_buffer).removeClass('hide');
}
};
}
};
$(
function() {
base.productFilterSetup();
});
//]]>
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" class="productFilter" name="form1" target='sendinfo' id='infoform' onsubmit='return displayResult()'>
<!-- Group 1 -->
<div class="step1 option0">
<label for="group_1">Qustion-1</label>
<select>
<option disabled selected class="drpdow">Select Option</option>
<option id="1" name="group_1" class="drpdow" type="dropdown" value="-A-Value" />
<label for="1">A</label>
<option id="2" name="group_1" class="drpdow" type="dropdown" value="-B-Value" />
<label for="2">B</label>
</select>
</div>
<!-- Group 2 -->
<div class="hide step2 option1">
<label for="group_2">Qustion-2</label>
<select>
<option disabled selected class="drpdow">Select Option</option>
<option id="1_1" name="group_2" class="drpdow" type="dropdown" value="-A-1-Value" />
<label for="1_1">A-1</label>
<option id="1_2" name="group_2" class="drpdow" type="dropdown" value="-A-2-Value" />
<label for="1_2">A-2</label>
</select>
</div>
<div class="hide step2 option2">
<label for="group_2">Question-2</label>
<select>
<option disabled selected class="drpdow">Select Option</option>
<option id="2_1" name="group_2" class="drpdow" type="dropdown" value="-B-1-Value" />
<label for="2_1">B-1</label>
<option id="2_2" name="group_2" class="drpdow" type="dropdown" value="-B-2-Value" />
<label for="2_2">B-2</label>
</select>
</div>
<!-- End of form -->
<p class="pResult" id="demo">
Result will display here
</p>
<p id="demo1"></p>
<input class="copyData" id="btn" type='submit' value='Display result' />
<button class="copyData" id="btnShow" type="button" onclick="clearResult()">Clear result</button>
</form>
I have a select with options that I am putting into an array, and I am attempting to alert a specific message when you click a button, but only if the proper array[x] has been selected. However, when I click the button, regardless of the option I get the message. What am I doing wrong?
Code:
HTML:
<button id="button">Click Me</button>
<br />
<br />
<select id = "list" value = "list">
<option id="one" value="one">
one
</option>
<option id="two" value="two">
two
</option>
<option id="three" value="three">
three
</option>
</select>
JS:
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list").selectedIndex;
for (var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if (selected = [1]) {
alert("hello");
}
};
You cannot compare arrays like this. You need to use literal number instead. JSFiddle
var listArr = [];
var button = document.getElementById("button");
var list = document.getElementById("list");
var selected = document.getElementById("list");
for(var i = 0; i < list.options.length; i++) {
listArr[i] = list.options[i].value;
}
button.onclick = function() {
if(selected.selectedIndex == 1) {
alert('hello');
}
};
If I have understood your question correctly, you need the updated value of the select:
button.onclick = function()
{
if(document.getElementById("list").selectedIndex==1) // Also change = to ==
{
alert("hello");
}
};
https://jsfiddle.net/6bs1vjva/1/
Do you know how to transfer data from listbox to another listbox ?
I have made one but it didn't stop submitting although I use a function to stop it from submitting .
You can look at my previous problem in this section
cancel-submit-code-not-working
The problem is not yet been solved even though there's few people helped me and I tried all their suggestions and recommendations but I always get the same result so I decided to ask you guys if there is someone who can do this using a javascript .
I tried to use one but it's not working because the function is for and I'm using LISTBOX so I think that's the reason why since I'm new to ASP.net C# javascript I can't change the code because ... it's not English :-D
hope you can change the code for me?
Here's the code for javascript
<script type="text/javascript">
function Listbox_transfer(Listbox_Orig, Listbox_Move) {
var moved = new Array();
var count = 0;
for (var item = 0; item < Listbox_Move.options.length; item++)
{
if (Listbox_Move.options[item].selected) {
var temp = document.createElement("OPTION");
temp.text = Listbox_Move.options[item].text;
temp.value = Listbox_Move.options[item].value;
var index = 0;
var currOpn;
while (index < Listbox_Orig.options.length && temp.text > Listbox_Orig.options[index].text)
{
index++;
}
if (index < Listbox_Orig.options.length)
{
currOpn = Listbox_Orig.options[index];
}
else
{
currOpn = null;
}
try
{
Listbox_Orig.Listbox_transfer(temp, currOpn);
}
catch (ex)
{
Listbox_Orig.Listbox_transfer(temp, index);
}
moved[count] = Listbox_Move.options[item].value;
count++;
}
}
if (moved.length > 0)
{
remove(Listbox_Move, moved);
}
}
function remove(Listbox_OrigRemoveFrom, items)
{
for (element in items) {
var index = 0;
while (index < Listbox_OrigRemoveFrom.options.length &&
Listbox_OrigRemoveFrom.options[index].value != items[element])
{
index++;
}
Listbox_OrigRemoveFrom.remove(index);
}
}
function addAll(Listbox_Orig, Listbox_Move)
{
var moved = new Array();
var count = 0;
for (var item = 0; item < Listbox_Move.options.length; item++)
{
var temp = document.createElement("OPTION");
temp.text = Listbox_Move.options[item].text;
temp.value = Listbox_Move.options[item].value;
var index = 0;
var currOpn;
while (index < Listbox_Orig.options.length && temp.text > Listbox_Orig.options[index].text) {
index++;
}
if (index < Listbox_Orig.options.length) {
currOpn = Listbox_Orig.options[index];
}
else {
currOpn = null;
}
try {
Listbox_Orig.Listbox_transfer(temp, currOpn);
}
catch (ex) {
Listbox_Orig.Listbox_transfer(temp, index);
}
}
removeAll(Listbox_Move);
}
function removeAll(list) {
for (var count = list.options.length; count >= 0; count--) {
list.remove(count);
}
}
function selectAll(Listbox_OrigSelect1, Listbox_OrigSelect2) {
for (var count = 0; count < Listbox_OrigSelect1.options.length; count++) {
Listbox_OrigSelect1.options[count].selected = true;
}
for (var count = 0; count < Listbox_OrigSelect2.options.length; count++) {
Listbox_OrigSelect2.options[count].selected = true;
}
}
I'm using input buttons
<input id="toTheRightButton" type="button" value=">>>" class="button button-primary" onclick="Listbox_transfer(this.form.ListBox3, this.form.ListBox2)"/>
Now here's the whole code of the demo that I tried to copy
<html>
<head>
<title>Lisbox Demo</title>
<script type="text/javascript" src="Listbox.js"></script>
</head>
<body>
<form method="post">
<table style="text-align: center" border="0">
<tr><td><strong>List 1:</strong><br/>
<select size="15" name="list1[]" id="list1" style="width: 350px" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select></td>
<td>
<br/>
<input type="button" value=">>" onClick="add(this.form.list2, this.form.list1)"/>
<br/><br/>
<input type="button" value="<<" onClick="add(this.form.list1, this.form.list2)"/>
<br/><br/>
<input type="button" value="All >>" onClick="addAll(this.form.list2, this.form.list1)"/>
<br/><br/>
<input type="button" value="All <<" onClick="addAll(this.form.list1, this.form.list2)"/>
</td>
<td><strong>List 2:</strong><br/>
<select size="15" name="list2[]" id="list2" style="width: 350px" multiple="multiple">
</select></td></tr>
</table>
<p> </p>
<p><select name="list3" size="14" multiple>
<option value="0">selection1</option></select> </p>
</form>
</body>
As you can see the code is for option list .. not for listbox for asp.net :-(
hope you can help me thank you .
Following function is for single item. you can modify it for all items and also make it single by passing listbox id as parameter:
function Add() {
var selectedItem = $("#lbAvailable > option:selected");
if (selectedItem.length > 0) {
selectedItem.remove().appendTo("#lbSelected");
$("#lbAvailable option:first-child").attr("selected", true);
$("#lbSelected option:last-child").attr("selected", true);
}
else {
alert("Select item");
}
}
function Remove() {
var selectedItem = $("#lbSelected > option:selected");
if (selectedItem.length > 0) {
selectedItem.remove().appendTo("#lbAvailable");
$("#lbAvailable option:first-child").attr("selected", true);
$("#lbSelected option:last-child").attr("selected", true);
}
else {
alert("Select item");
}
}
function AddAll() {
$("#lbAvailable option").each(function () {
this.remove().appendTo("#lbSelected");
});
}
function RemoveAll() {
$("#lbSelected option").each(function () {
this.remove().appendTo("#lbAvailable");
});
}
I don't know js. I need to get the multiple selection as comma separated from select box into a text input.
with pure js, I found only this question related on SO. Multiple selections into input box
And I tried the js code in that question. (question js combination with accepted answer)
However I couldn't achieve.
what I need is for example printing Australia,England into text input after selecting those 2 and submitting.
Fiddle link is:
http://jsfiddle.net/0k2m7gLo/
CODE IN FIDDLE
HTML
<form>
<select id="countries" multiple>
<option value="val0">Australia</option>
<option value="val1">England</option>
<option value="val2">France</option>
</select>
<input type="button" value="Show Index" onclick="showSelected();" />
</form>
<p>selected countries by comma seperated</p>
<form><input type="text" id="txtText" /></form>
UNSUCCESSFUL JS
function showSelected()
{
var selObj = document.getElementById('countries');
var txtTextObj = document.getElementById('txtText');
var selIndex = selObj.selectedIndex;
txtTextObj.value += selObj.options[selIndex].text +', ';
}
You can do something like this:
var selObj = document.getElementById('countries'),
txtTextObj = document.getElementById('txtText'),
selected = [];
for(var i = 0, l = selObj.options.length; i < l; i++){
//Check if the option is selected
if(selObj.options[i].selected){
selected.push(selObj.options[i].textContent);
}
}
txtTextObj.value = selected.join(', ');
jsFiddle
function updateSelected() {
var select = document.getElementById('countries'),
options = select.options,
input = document.getElementById('selected');
var selected = [];
for (var i = 0, ii = options.length; i < ii; ++i) {
var opt = options[i];
if (opt.selected) {
selected.push(opt.innerHTML);
}
}
input.value = selected.join(', ');
}
in my form
<div class="container">
<select name="sel1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="sel2">
<option value="0">Zero</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<input type="button" onclick="resetAll()" value="Reset"/>
i need to reset both sel1,sel2 to default values. ie selectedIndex = 0;
function resetAll()
{
//what should i write here to do this
}
i have more than 20 selectboxes. any help?
Simply add an id to the container item, so you can easily reference it. This way you only reset the select boxes that reside in it, and not any other ones you may have on the page:
function resetAll() {
var container = document.getElementById('container');
var children = container.getElementsByTagName('select');
for (var i = 0; i < children.length; i++) {
children[i].selectedIndex = 0;
}
}
Try this, this should work for any number of drop downs
function resetAll()
{
var selects = document.getElementsByTagName('select');
var len = selects.length;
for(var i=0; i<len; i++){
selects[i].selectedIndex=0;
}
}
Demo: http://jsfiddle.net/LAaRv/1/
UPDATE:
If you want to reset only "sel1" and "sel2" then try this,
function resetAll()
{
var selects = document.getElementsByTagName('select');
var len = selects.length;
for(var i=0; i<len; i++){
if(selects[i].name == "sel1" || selects[i].name == "sel2"){
selects[i].selectedIndex=0;
}
}
}
Simply Without using any for loop -
For First Index -
$("select").each(function() { this.selectedIndex = 0 });
For Empty Selection -
$("select").each(function() { this.selectedIndex = -1 });
PLUNKER EXAMPLE
Try this
var secondCombo = document.getElementsByName("sel1")[0];
secondCombo.value = 0;