I have a problem where I have multiple select buttons in a form and onclick on each button should select different options of the same selectbox. The below code works fine if I pass a value while onclick but the old value is retained if no value is passed instead of setting it to nul.
Tried formname.reset() before selecting an option to refresh, but this is not selecting any value at all.
For eg, select1 is clicked and first value of select box is selected. After clicking select2 instead of resetting itself to null, it shows the old value (1). Select3 works fine again selecting the second value of the select box.
<script>
function editvalues(arr)
{
$('#parent_id option[value='+arr+']').attr('selected','selected');
}
</script>
Select1
Select2
Select3
<select id="parent_id" name="parent_id">
<option value=''>Select Any</option>
<option value='1'>First</option>
<option value='2'>Second</option>
</select>
Se the value to '' in case no argument is passed.
$('#parent_id option[value='+(arr || '')+']').attr('selected','selected');
In the above code, (arr || '') will return arr if it is passed to the function. Else it will return '' (which happens to be the value of the <option> that represents no selection).
In your case using val method will solve the issue:
function editvalues(arr) {
$('#parent_id').val(arr);
}
However you should consider using jQuery more rather then old-school inline handlers approach. For example:
Select1
Select2
Select3
JS:
$('.select').on('click', function() {
var val = $(this).data('value');
$('#parent_id').val(val);
});
Demo: http://plnkr.co/edit/iuFEjBKkQZZEpk8keaqx?p=preview
You can deselct any selection 1st:
function editvalues(arr)
{
//deselect 1st
$("#parent_id option:selected").prop("selected", false)
//then select passed in value
$('#parent_id option[value='+arr+']').attr('selected','selected');
}
Related
I'm currently working on a dynamic form which enables the user to add as many variants as they would like. This form which can be added has a price, size and color. The size and color are select2 select boxes which enable the user to select multiple things. The form:
<div class="col-sm-4">
<label>Kleuren</label>
<select name="colors[{{$i}}][]" id='color-options' class="form-control multiple-select" multiple="multiple">
#foreach($colors as $id=>$color)
<option value="{{$id}}">{{$color}}</option>
#endforeach
</select>
</div>
When looking at the HTML code I have multiple of these forms which go by name: colors[0][], colors[1][], colors[2][] etc.
How do I print the value of a selected new color in a new div? The code which I have thus far:
$(document).ready(function() {
$('.multiple-select').select2({
language: 'nl'
});
$('.summernote').summernote();
var addVariantButton = document.getElementById('addVariant[0]');
addVariantButton.addEventListener('click', function(){
addVariant(0);
});
var colorSelected = document.getElementsByName('colors[0][]');
colorSelected.addEventListener("click", displayColorSelected);
});
function displayColorSelected() {
var selected_value = document.getElementById("color-options").value;
console.log(selected_value);
}
But this only works for the first colors input form, but how can I make this into a more dynamical function to get all colors input?
You can get all selected values in array as below:
function displayColorSelected() {
var selected_value = $("[id='color-options']").toArray().map(x => $(x).val());
console.log(selected_value);
}
Note: id selector will always return single element which will be first with that id. So you're getting value for first select only.
You can use attribute selector ([]) instead which will find every element with given id. So here $("[id='color-options']").toArray() will find every element with id equal to color-options and map(x => $(x).val()) will return only value part from the elements array.
Add all the selects a class ("color-select" for example), and run over all the selects -
$('.color-select').each(function() { console.log($(this).val()); })
You may need to delegate your event listener
document.addEventListener('event',function(e){
if(element){//do something}
})
Since you are using jquery its easier
$(document).on('event','element',function());
I have a select box with 3 option, and a div with 3 that they has data attribute.
now i want each option that has selected=seclected and also value (number) equal with a data then add class to
for example:
if option selected / and value = with data:
<option value="2" selected="selected">
do (add class):
<a class="menuitem active" data="2"></a>
JSFiddle
$("#myselect option").each(function(){
var num = $('.menucontainer').children('a.menuitem').attr('data');
if($(this).is(':selected').val()==num){
$('.menucontainer').children('a.menuitem').addClass('active');
}
});
});
You had many small mistakes. Like
1.) Jquery was not included in fiddle.
2.) .is returns a boolean value, and you were doing $(this).is(':selected').val(). You should be doing $(this).is(':selected') && $(this).val().
3.) There was }); extra in the end.
And I think iterating other way arround will be better. Like bellow
$('.menucontainer .menuitem').each(function(){
if($(this).attr('data')==$('#myselect :selected').val())
$(this).addClass('active');
})
DEMO
Below is code for select option and generate using php from database and i try to add selected="selected" to value="4" using jQuery or any javascript:
<select id="countryselect" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">Malaysia</option>
<option value="5">Maldives</option>
</select>
i try to refer this post but still can't .. below is my current script :
<script>
localStorage.setItem("Select1", "Malaysia");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>
thanks.
The selected attribute is a boolean attribute, its presence sets the value of the related DOM property to true. If the attribute is absent, the value of the selected property is false.
If an option has the selected attribute, then when the page is first loaded, or the form the control is in is reset, that option will be the selected option.
If the option's selected property is set to true, then that option will be selected. However, if the form is reset, the default selected option will be selected (i.e. the one with the selected attribute, or the first option, or none).
To set the selected attribute (i.e. make the option the default selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.setAttribute('selected', true);
// For a single select, the job's done
return;
}
}
Note that this may not make the option the currently selected option, it will just add the selected attribute. To make sure it's selected (if that is what is required), the also set the selected property to true (see below).
Note that the second argument to setAttribute is supposed to be a string that is used to set the attribute's value. However, the selected attribute doesn't have a "setable" value, so the second argument is ignored (e.g. even false will still set the attribute and make the option the default selected option). That causes some confusion. :-)
To set the selected property (i.e. just make the option the current selected option):
var select = document.getElementById('countryselect');
var option;
for (var i=0; i<select.options.length; i++) {
option = select.options[i];
if (option.value == '4') {
// or
// if (option.text == 'Malaysia') {
option.selected = true;
return;
}
}
This should work simple, $("#countryselect").val('4')
It will automatically set selected=selected
Demo: http://jsfiddle.net/muthkum/zYRkC/
localStorage.getItem("Select1") will return Malaysia and $(e).val() will return 1,2...5 in each loop. So your condition will never be true. Instead use
<script>
localStorage.setItem("Select1", "4");
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem("Select1")){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>
As of jQuery 1.6 "To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method."
$("#countryselect option[value=4]").prop("selected", "selected")
Just try
$("#countryselect").val('4')
//OR
$("#countryselect option").val('4').attr("selected", true)
Check this FIDDLE
$('#countryselect > option[value *= "4"] ').attr('selected',true);
this will work
I have the following select field and based on whether the class .show-x-trend or show-x is selected I would like to conditionally reveal a separate div. If .show-x-trend <option> is selected, I'd like to reveal the already hidden #x-axis-trend-wrap <div> and if show-x option is selected I'd like to reveal the already hidden #x-axis-wrap <div>. In the code below, you'll see that I have both CSS classes and also values assigned to the 3 selection options because I tried to achieve the effect a few different ways but so far with no luck.
<div id="visualize-wrap">
<h3>Visualization Shows</h3>
<select id="visualize-shows" name="visualize">
<option class="no-show" value="00">Select One</option>
<option class="show-x-trend" value="01">Trend Over Time</option>
<option class="show-x" value="02">Breakdown of Sum Total</option>
<option class="show-x" value="03">Side-by-side Comparison</option>
</select>
</div>
You can use hasClass method to determine if the selected option contains the required class or not and act accordingly.
$('#visualize-shows').change(function(){
var $selectedOption = $(this).find('option:selected');
$('#x-axis-trend-wrap')
.toggle( $selectedOption.hasClass('show-x-trend'));
$('#x-axis-wrap')
.toggle( $selectedOption.hasClass('show-x'));
});
Working demo - http://jsfiddle.net/X2dPt/
Try something like this
$("#visualize-shows").change(function() {
$selected = $(this).find('option:selected'); // get selected option
if ($selected.hasClass('show-x-trend')) { // check the class
$('#x-axis-trend-wrap').toggle(); // toggle display
} else if ($selected.hasClass('show-x')) {
$('#x-axis-wrap').toggle();
}
});
this uses .hasClass()
I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});