Button to add selected="selected" from outside form - javascript

I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.

Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>

For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>

Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.

Related

How do you properly "reset" a <select> element that supports multiple options in regular JS?

I want to be able to reset <select> tags by themselves instead of making them reset with the entire form. This is what I have so far:
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
And the JS:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
selectedOptions[i].selected = false;
}
}
When I first tried this, it seemed to work. However, only when one option is selected. I've noticed that when there is more than one option currently selected, it seems to break.
Starting with three options, and clicking the Reset button results in this, for some reason:
Every option gets deselected apart from one. Why does this happen?
Clicking the Reset button again deselects the one still selected option though.
You can set the selectedIndex attribute to -1 to indicate that no element is selected.
function resetS() {
const multipleSelect = document.getElementById('s');
multipleSelect.selectedIndex = -1;
}
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
The list of selected <option> elements is a "live" list. When you change the selected flag on one of the elements, the list changes; that is, the <option> you changed disappears from the list, so the length gets 1 shorter. An indexed for loop will therefore skip elements.
The way to deal with that (well, one way) is to use a while loop as follows:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
while (selectedOptions.length) {
selectedOptions[0].selected = false;
}
}
edit — or you could use the method suggested in Tom's answer, which is simpler.

Is it possible to get a reference of the array of selected values on a Select2?

I have a select2 which is multiple select.
There are two ways to select an option:
Type and choose on the select box,
There is a menu on which you can click and it will add it to the select2 select box.
It's not properly working this time, but I can already select options using the menu.
What I want to know is, is it possible for me to have a reference of the array of selected values?
Because what I am doing right now is,
I have an array called, selectedValuesArray,
where when I select from the menu, it will push the id of the selection to the selectedValuesArray and
$('#selectbox').val(selectedValuesArray).trigger("change");
So can I just have a reference on the array of the selected value itself so I'll just push and splice items there?
EDIT:
Select2.val() is an array.
I want to have a reference to that array like,
var selectionArray = Select2.val();
And I want to manipulate that array dynamically.
// like adding a selection
selectionArray.push("1");
// or removing a selection
selectionArray.splice(indexOf("1"), 1);
Is it possible?
If I've understood your question properly, you're after something like this:
$("#e1").select2();
$("#checkbox").click(function () {
if ($("#checkbox").is(':checked')) {
$("#e1 > option").prop("selected", "selected");
$("#e1").trigger("change");
} else {
$("#e1 > option").removeAttr("selected");
$("#e1").trigger("change");
}
});
$("#button").click(function() {
console.log($("#e1").val());
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css">
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="checkbox" id="checkbox" />Select All
<input type="button" id="button" value="Check Selected" />
Original fiddle can be found here.
Alright I have managed to achive what you want. Here is the code;
var selectedArray = $('#selectbox').val();
var selectElem = $('#selectbox').select2();
//delete '42' from array
var index = selectedArray.indexOf('42');
data.splice(index,1);
selectElem.val(selectedArray);
selectElem.trigger('change');
//add '52' to array
selectElem.push('52');
selectElem.val(selectedArray);
selectElem.trigger('change');
Hope this helps :)

Toggle element when value is selected without know any information about value

I've a problem here and don't know the right path to get this working. I have a table where I store some values and of course I can do CRUD operations on any records. Those values are used to build a SELECT element dynamically. All this works perfectly but I need to toggle one element visibility when specific value is picked. For example:
<select class="change">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<input type="text" class="show" style="display:none" />
Taking this as input, by default .show is hide, lets said that any time I choose "Value 2" it will be displayed otherwise should be hidden again. I know how to do this at jQuery with this code:
$(".change").on('change', function() {
option = $('.change :selected').val();
if (option == "Value 2") {
$(".show").show();
} else {
$(".show").hide();
}
});
But what's happen if any edit "Value 2" and change it to "VAlue 2" or "VALue 2" or "Value2"? The code will stop working. In this case what did yours do to avoid this?
I can attach to "ID" but again what's happen if any deletes the record with ID=2 and recreate later with ID=10? Then code will stop working again.
I don't know how to get this done, any advice? Ideas? Workarounds?
I guess you are building your dropdown list using data from DB. What I suggest is to add a new column in your table. This column will be a simple bool to determine if your input needs to be hidden or no.
Then you have this HTML code (here new col is "showInput"):
<select class="js-dropdown">
<option value="foo" data-showInput="1">Foo</option>
<option value="bar" data-showInput="0">Bar</option>
<option value="foobar" data-showInput="1">Foobar</option>
</select>
<input type="text" class="js-input" />
And this JS code:
var input = $(body).find('.js-input');
$('.js-dropdown').on('change', function() {
var option = $(this).find(':selected');
var showInput = parseInt(option.attr('data-showInput'));
if (showInput === 1) {
input.show();
} else {
input.hide();
}
});

Add/Removing Options with JQuery

I'd like to add and remove options from one drop down menu using JQuery given a selected option in another.
HTML:
<form action='quickLook.py' method = 'post'>
First DropDown Menu
Specify Channel:
<select id='bolometer'>
<option selected id='Dual' value = 'Dual' >Dual
<option id='Top' value = 'Top' >Top
<option id='Bottom' value = 'Bottom' >Bottom
</select>
Second DropDown Menu
<br>Specify Data to Display:
<select id='target'>
<option selected id='Spectrum' value = 'Spectrum'>Spectrum
<option id='Interferogram' value = 'Interferogram'>Interferogram
<option id='SNR' value = 'SNR'>SNR
<option id='Diff_Band' value = 'Diff_Band'> Diff_Band
</select>
<input type='submit' value= 'Query Images'>
</form>
I'd like to do something like this is JQuery:
$("#Dual").click(function() {
$("#target").append("#Diff_Band");
$("#target").remove("#Interferogram");
$("#target").remove("#SNR");
});
$("#Top").click(function() {
$("#target").append("#Interferogram");
$("#target").append("#SNR");
$("#Diff_Band").remove();
});
I want to append or remove the already written html.
What is the best way to do this?
Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/

More Properties of Dropdown options

I've got a dropdown setup going on in which the user enters an input value, chooses a calculation to perform on that number from a dropdown, then a function displays the result.
What I would like is to add more 'values' to the dropdown, so when an option is selected from the list, it can also, say, display some text stored in the list, or some other information. Right now I can return the selected option's value (.value) and use the option's name (.text) to perform functions, but is there any more data I can add to each selection to be used later?
<html>
<head>
<script language="JavaScript">
function myfunction(form)
{
var i = parseFloat(form.Input.value, 10);
var e = document.getElementById("calculationList");
var strUser = e.options[e.selectedIndex].value;
form.Output.value = strUser*i;
}
</script>
</head>
<body>
<form>
Input Number:
<INPUT NAME="Input" SIZE=15>
Make a selection:
<select id="calculationList" onchange="myfunction(form)">
<option></option>
<option value="2">Double It</option>
<option value="3">Triple It</option>
<option value="10">Multiply It By ten</option>
</select>
Output Number:
<INPUT NAME="Output" SIZE=15>
</FORM>
</body>
</html>
Basically you may attach data attribute to your options like that:
<select id="calculationList">
<option></option>
<option value="2" data-aaa="10">Double It</option>
<option value="3" data-aaa="20">Triple It</option>
<option value="10" data-aaa="30">Multiply It By ten</option>
</select>
And later get the content of the attribute:
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
jsfiddle -> http://jsfiddle.net/pzKrr/
Edit:
If you want to implement my solution remove onchange="myfunction(form)" from the select tag. After that add the following code just after that myfunction
window.onload = function() {
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
};

Categories