Change selectbox selection on img click - javascript

When someone clicks a specific link on my website I want the select box option to change to the option to a certain option by the value it has set.
I imagine I would do this by adding some sort of onClick that points to the value on each selection... but can't figure out the code to use.

In regular JavaScript you could do something similar to:
var selectBox = document.getElementById('selectBox');
var image = document.getElementbyId('someImage');
image.addEventListener('click', function() {
selectBox.selectedIndex = 1; // specify the selected index here.
});
where you get a reference to the select box and image and add an event handler to the image to set the selected index of the select box.
If you have jQuery available, you can do similar:
$('img').click(function() {
$('select').val('new value'); // specify the new value
});

Related

Select options disappearing when appending new option

I'm currently creating a interface to select an option from one select element on double click, and append it to another select element.
The issue I am coming across is when doing so, it is added and visible, however all other options disappear in the destination select, until I click on the option and then click off.
You can see this in action here: https://i.imgur.com/jSXoIAi.gifv
My current implementation is as follows:
$('body').on('dblclick', '#availableColumnsSelect > option', function (e) {
var option = $(this);
//Add option to destination
displayColumnsSelect.append($('<option>', { value: option.val(), text: option.val() }));
//Remove option from source
option.remove();
//Sort the select options
sortSelect("#displayColumnsSelect");
var optionsAvailable = $("#availableColumnsSelect > option:not([disabled])").length;
if (optionsAvailable == 0) {
$("#noSelectedText").removeClass('hidden');
}
$("#noSelectedText").addClass('hidden');
});
The underlying HTML is being constructed exactly how it should.
Any ideas?
As pointed out the issue was with the sortSelection function. I'm not quite sure why, but regardless I don't actually require this function anymore.
Removing said function has resolved the issue :)

move the result of select2 to the other div

I am using select2 and I use it for a single choice. I want to move the result of what we have chosen to another div.
Please check my code:
https://jsfiddle.net/hxe7wr65/
How to move it? because I don't want the result to show in the box. I want the box still clear and even after I choose, the placeholder still shows up.
This is the design that i'm doing right now
in that image. its only can choose 1 option. after we choose. the result show up to another place and so the select still have the placeholder in it. please guys help me.
thank so much
Ok I'm not 100% sure this is what you're looking for, but I think you wan't the grab value of the last selected item, transfer it to another div and then clear the input.
For the first step add an event handler to it.
var $eventSelect = $("#position"); //select your select2 input
$eventSelect.on('select2:select', function(e) {
console.log('select')
console.log(e.params.data.id) //This will give you the id of the selected attribute
console.log(e.params.data.text) //This will give you the text of the selected text
})
Now that you have the value, transferring it to the other div is relatively simple.
var $eventSelect = $("#position"); //select your select2 input
$eventSelect.on('select2:select', function(e) {
var text = e.params.data.text
$("#otherdiv").append(text)
})
Then to clear the form
var $eventSelect = $("#position"); //select your select2 input
$eventSelect.on('select2:select', function(e) {
var text = e.params.data.text
$("#otherdiv").append(text)
$(this).val('');
// or depending no what version you are using
$(this).select2('val', '')
})

Multiple select - value of deselect returns null

Description
I am using a jquery plugin chosen which pretty much does something like this:
This lets me add each option one by one or remove each option one by one. For every option selected, I create a new element with the selected option's value as the id.
Problem
The problem is when I remove an option from the list. For example:
$('#multiple-select').on('change', function(e){
alert($(e.target).val());
});
Will return the correct value if an option is added, however it returns null if we remove an option. I need to be able to get the value of the option being deselected so I can remove it in the other element.
Question
How can I get the deselected option's value to return the actual value instead of null? Or is there another way to bypass this problem?
All I need to be able to do is find the option being deselected and removing it from the other element (knowing that the element's id is built on the option's value).
Update
Remove code as requested:
$('body').on('change', benefs, function(e){
var $nbparts = $(participantNbParts),
$target = $(e.target),
$val = $target.val(),
$name = $target.text();
if($val == null){
//this is because we deleted something thus we need to remove it from $nbparts which is a pitty since we don't know what it was before it got deleted
}else{
//someone was added
$(create_row_expense_nb_parts_participant($name, $val)).appendTo($nbparts).show('slow');
$nbparts.parent().show('fast');
}
});
jQuery chosen provides selected and deselected using which you can identify selected and deselected values respectively, like:
$("#your_element_id").on('change', function (evt, params) {
var selected = params.selected;
var removed = params.deselected; //gives you the deselected value
//assuming your option ids are numbers
if( removed > 0 ) {
console.log( "Value removed is:" + removed );
}
});
From its documentation in the change event description you have
Chosen triggers the standard DOM event whenever a selection is made
(it also sends a selected or deselected parameter that tells you which
option was changed).
This suggests you should observe the arguments received by the event handler at run time to get a hint about (and most likely a reference to) the removed/deselected option.

jQuery - Get the value of unselected item in multiselect

Although this may sound dead simple, the matter is complicated by the fact I can only use the change() trigger on the select element. I am using the 'Chosen' jQuery plugin which basically modifies the multi select box on the page.
Whenever a item is selected or unselected, the plugin triggers the change event on the original select element. I am obviously able to get all the unselected items, but I need the one that was just unselected that caused the change event to trigger.
So I have the following function, the bit in the middle is what I need to capture the item that was just unselected. #cho is the id of the original select element.
$("#cho").chosen().change( function() {
// Need code here to capture what item was just unselected, if any...
})
Store value when the user changes the the check box.
var preVal;
$("input[name='g']").on("change",function(e){
if(preVal){
alert(preVal);
}
preVal=$(this).val();
});
Check this http://jsfiddle.net/fcpfm/
1.Use hidden field
2.Hidden field value initially empty.
3.Onchange put the selected value in a hidden field.
4.If onchange is happening again , hidden field value is the previously selected value.
$("#cho").chosen().change( function() {
var hidvalue = $('#hiddenfield').val();
if (hidvalue ) {
//Get the previously selected ids
var prev_ids = $('#hiddenfield').val();
//Then Update currently selected ids
$('#hiddenfield').val('currently selected ids');
} else {
//Update currently selected ids
$('#hiddenfield').val('currently selected ids');
}
})
Try using a variable to store the selected item. Update it each time when item changed. I cant add comment. That is why I am posting it as an answer.

Dynamically add option to chosen select multiple JQuery plugin

I want to add the text that a user inputs in the text field of a chosen select multiple input as an option, and automatically select it, all of this when the option doesn't exists, if the option exists, then I would like to select it. So far I have manage to do this:
Chosen.prototype.add_text_as_option = function () {
$('#id_select').append(
$('<option>')
.html(this.search_field.val())
.attr('selected', 'selected')
.attr('value', 0)
);
$('#id_select').trigger("liszt:updated");
return false;
};
I call this function whenever the users presses enter while the input field is in focus within the keydown_check function.
I have two problems:
Top priority, when the user presses enter and has typed a substring of an option, the option won't get selected, but the substring text will be added and selected. Not what I want.
For instance: If I have the option "foo", and start typing "fo", chosen will mark the first
option as candidate ("foo"), so if I press enter, it should be selected, but instead, what happens is that "fo" is added as an option and selected, when I actually wanted to select "foo".
If I select "foo" with a click, then everything works fine. The option chosen marks is selected and the substring text is taken as part of the option.
How can I add a non existent option to chosen, without loosing all the original functionality?
How can I access the select multiple field I initilized whith chosen inside the chosen plugin? As you can see in the code above, the id of the select multiple field is hardcoded. I want to do this to be able to refresh the select when the user adds a new option.
The functionality that I'm looking for is very similar to the skills widget of linkedin
You should try out the select2 plugin which is based off of chosen plugin but it works well with adding elements dynamically.
Heres the link: http://ivaynberg.github.com/select2/
Look at the example for auto-tokenization I think that might be what you are looking for.
I needed this today so I wrote something like this:
$(function() {
// form id
$('#newtag').alajax({
// data contains json_encoded array, sent from server
success: function(data) {
// this is missing in alajax plugin
data = jQuery.parseJSON(data);
// create new option for original select
var opt = document.createElement("OPTION");
opt.value = data.id;
opt.text = data.name;
opt.selected = true;
// check if the same value already exists
var el = $('#tags option[value="' + opt.value + '"]');
if( !el.size() ) {
// no? append it and update chosen-select field
$('#tags').append( opt ).trigger("chosen:updated");
} else {
// it does? check if it's already selected
if(!el[0].selected) {
// adding already existent element in selection
el[0].selected = true;
$('#tags').trigger("chosen:updated");
} else {
alert("Already selected and added.");
}
}
}
})
});
"#"newtag is a form, ".alajax" is a plugin that sends form data in async way and returns server's response in JSON format. In the controller I check if a tag exists otherwise I create it. In response I five "jsoned" tag object.
I created a jsfiddle of jquery chosen which takes text and create as option. In earlier version of jquery chosen have facility create option.
create_option: true;
persistent_create_option: true;
skip_no_results: true;
You can use this code:
$('#id_select').chosen({
width: '100%',
create_option: true,
persistent_create_option: true,
skip_no_results: true
});
jsfiddle link: https://jsfiddle.net/n4nrqtek/
just call it keyup_check
keydown_check is called before the pressed letter is initialized
unlike keyup_check
I found a solution multiple select
var str_array = ['css','html'];
$("#id_select").val(str_array).trigger("chosen:updated");

Categories

Resources