Edit:: What I am trying to achieve is I am getting each option text not the value, so I can send it to an API. Getting the text from the select works perfectly. I want to remove it when I deselect an option from the input value when I click it again. For example if I select multiple I get Medit-4-packs, Swiss-Gear-Bag When I click it one by one it removes it but when I deselect multiple I get the value of another. I want to replace the value as empty when deselected like usual. Hope it helps to clarify
Any help on using jquery to deselect Select option from input value? These are what I have tried so far. Thanks for help
Trying to remove the values in the <input> when option gets deselected.
<input class="form-check-input" type="text" value="" id="equipment" name="equipmentitems" >
<select multiple class="image-picker show-labels show-html" data-limit="16" name="packages[]" id="group_psoft">
<option value=" " data-img-class="first" selected></option>
<option data-img-src="/images/" data-img-label="Scanner Tips(4Pcs)" name="packs" data-img-alt="KeepSame" value="400" >Medit-4-packs</option>
<option data-img-src="/images/" data-img-label="SwissGear Bag" name="bagoriginal" data-img-alt="Aggresive" value="200"> Swiss-Gear-Bag</option>
</select>
Js
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
$('#equipment').val($(this).unbind('option:selected').text()); // This removes it but add all the other options text in the input
$('#equipment').val($(this).unbind('option:selected').val( )); // Here It removes it but I get the value of the next selected option.
$('#equipment').val($(this).unbind('option:selected').text(' ' )); This I get Js [object,object]
}
});
I solved it when I move the code outside the function. I also changed unbind() to on() method.
$('.image-picker').on('change', function() {
$('#equipment').val($(this).find('option:selected').text());
});
Try this and see if it works out.
$('.image-picker').imagepicker({
show_label: true,
limit: 15,
//This is setting the text in the input
selected: function($items) {
$('#equipment').val($(this).find('option:selected').text());
},
// Here I want to remove it if clicked again
changed: function(){
var equiValue = $('#equipment').val();
var selectedValue = $(this).find('option:selected').text();
if(equiValue === selectedValue) {
$('#equipment').val("");
}
}
});
I have five dropdownlists on the form. I want that if user select something from one of dropdownlists, the other ones should be unselected. User can select something from just one dropdownlist.When he select something,selected value of other dropdownlists should be unselected. I'm using jquery
#foreach (var lay in Model.EventLayouts)
{
<li>
<select class="layoutSelect" layoutname="#lay.Name" layoutId="#lay.LayoutID" moderation="#lay.Moderation.ToString().ToLower()" selectedVal="0">
<option value="0">#PageResources.Quantity</option>
<option value="1">1</option>
</select>
</li>
}
Assuming that both dropdown has same class="layoutSelect" and unselect value="0", try below jQuery :
$('.layoutSelect').change(function(){
$('.layoutSelect').not(this).val('0');
});
Demo
Try this way
$(document).on('change', '.layoutSelect', function () {
if ($(this).find('option').is(":selected")) {
$('.layoutSelect').not($(this)).val("");//val('0');
}
});
DEMO
If you are trying to reset the other drop-downs but not the one which is changed, by adding same class on all drop-down you can do like this:
$(".layoutSelect").change(function(){
$(".layoutSelect").not(this).val(0);
})
FIDDLE EXAMPLE
I got one text box and one select box.
<input type="text" />
<select>
<option value=1>Test1</option>
<option value=2>Test2</option>
</select>
Now i want when user type anything in text box, to change value=2 text.
I tried this, but looks like don't work.
$(document).ready(function () {
$("#textbox").keyup(function () {
$("select#sync[value='2']").text($(this).val());
});
});
Apart from the fact that you haven't given the elements IDs, the problem is that you need to access the <option> element (that one has a value of 2 - there is no <select value=2>). Also, IDs are unique, so using select#sync is (should be) the same as #sync:
$("#sync option[value='2']")
<input type="text" id="textbox" />
<select>
<option value="1">Test1</option>
<option value="2">Test2</option>
</select>
$(document).ready(function () {
$("#textbox").keyup(function() {
$("select option[value='2']").text($(this).val());
});
});
http://jsfiddle.net/gxaWE/
you can try
$("#sync").val($(this).val());
provided that the user only types the value that is in range
DEMO
$("#text_box").keyup(function() {
$("#sync option[value='2']").text($(this).val());
});
Here is fiddle showing it working:
http://jsfiddle.net/bRw8Z/1/
It changes select option number 2 text. Is that what you wanted?
I see a few problems here:
It doesn't make sense to set the innerText of a <select> element; you want to set its value instead,
The #textbox selector wouldn't actually select anything.
If your input did not exactly match an <option>'s value attribute, the first <option> would be selected.
This snippet will select an <option> if its value attribute matches the value of the text input.
$(document).ready(function () {
$("input").keyup(function () {
var $select = $("select"),
value = $(this).val();
if($select.find('option[value="' + value + '"]').length){
$select.val(value);
}
});
});
http://jsfiddle.net/2XxRQ/1/
I've got a multiple select that I want to use to pick which elements show up in an HTML template window. So I have several options that I want to iterate over, and based on whether it's been selected, make the preview elements visible or hidden.
I'm going for something like this:
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
$(??????).css($css);
});
As you can see, I'm just iterating over each option (I'm pretty sure that syntax works) in my area_select menu, but I don't know how to make the css get applied to the corresponding piece.... how can I reference my preview elements via my options?
An easier way to go is to call .val() on the multiple select. That returns an array of selected values that you can iterate over.
var array = $('#area_select').val()
$.each(array, function(i,val) {
// your code
});
So as far as showing the elements is concerned, it would depend on what type of data is stored in the value of the select options.
For an ID, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('#' + value).css('visibility','visible');
});
Or if they are class names, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('.' + value).css('visibility','visible');
});
Give each of the options a name corresponding to the ID of the correct piece.
e.g.
<select>
<option value="whatever">Whatever</option>
<option value="whatever2">Whatever 2</option>
</select>
Then each of you elements will be contained in a a div like this:
<div id="whatever-preview">
<!-- Whatever -->
</div>
Then your Javascript
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
var div_name = "#" + $(this).attr('value') + "-preview";
$(div_name).css($css);
});
Give each option an id referencing the id of the corresponding element in the preview window.
for instance:
<option id="option-1">This turns on the first option element in the preview window</option>
<option id="option-2">This turns on the first option element in the preview window</option>
and give the preview window elements similar-ending ids:
<div id='window-1'>corresponding window preview element</div>
Then in the javascript:
$("#window-" + $(this).attr('id').split('-')[1]).css($css);
First, give the elements to hide or show the same class but id's matching the options values:
<div class="something" id="val_1">content1</div>
<div class="something" id="val_2">content2</div>
<div class="something" id="val_3">content3</div>
<div class="something" id="val_4">content4</div>
<select id="area_select">
<option value="val_1">val 1</option>
<option value="val_2">val 1</option>
<option value="val_3">val 1</option>
<option value="val_4">val 1</option>
</select>
then, when the select choosen option changes hide all the stuff and show the selected
$('#area_select').change( function(){
var val = $(this).val();
$('.something').hide();
$('#'+val).show();
return false;
});
Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id="mySelect" size="9"> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution..
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
why not just use plain javascript?
document.getElementById("selectID").options.length = 0;
If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:
$('#mySelect').find('option:not(:first)').remove();
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.
$(function() {
$('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
$("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
// Bind click event to each radio button.
$("input[name='myRadio']").bind("click",
function() {
switch(this.value) {
case "1":
$('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
break ;
case "2":
$('#mySelect').find('option').remove() ;
var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
var options = '' ;
for (var i = 0; i < items.length; i++) {
if (i==0) {
options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
}
else {
options += '<option value="' + items[i] + '">' + items[i] + '</option>';
}
}
$('#mySelect').html(options); // Populate select box with array
break ;
} // Switch end
} // Bind function end
); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input name="myRadio" type="radio" value="1" /></label>
<label>Two<input name="myRadio" type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.
var ClearOptionsFast = function(id) {
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
More info here.
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
The first line of code will remove all the options of a select box as no option find criteria has been mentioned.
The second line of code will add the Option with the specified value("testValue") and Text("TestText").
Building on mauretto's answer, this is a little easier to read and understand:
$('#mySelect').find('option').not(':first').remove();
To remove all the options except one with a specific value, you can use this:
$('#mySelect').find('option').not('[value=123]').remove();
This would be better if the option to be added was already there.
How about just changing the html to new data.
$('#mySelect').html('<option value="whatever">text</option>');
Another example:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
First clear all exisiting option execpt the first one(--Select--)
Append new option values using loop one by one
$('#ddlCustomer').find('option:not(:first)').remove();
for (var i = 0; i < oResult.length; i++) {
$("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
}
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
I saw this code in Select2 -
Clearing Selections
$('#mySelect').val(null).trigger('change');
This code works well with jQuery even without Select2
Cleaner give me Like it
let data= []
let inp = $('#mySelect')
inp.empty()
data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))
save the option values to be appended in an object
clear existing options in the select tag
iterate the list object and append the contents to the intended select tag
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};
$('#selectID').empty();
$.each(listToAppend, function(val, text) {
$('#selectID').append( new Option(text,val) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I used vanilla javascript
let select = document.getElementById("mySelect");
select.innerHTML = "";
Hope it will work
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
The shortest answer:
$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
Try
$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");
OR
$('#mySelect').html('<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);