How to remove an option from a select element with Select2 applied? - javascript

So, I have this HTML code:
<input type="checkbox" id="orders_lives_in_ccs" name="orders[lives_in_ccs]" class="lives_in_ccs">
<select id="orders_shipping_from" name="orders[shipping_from]" required="required" class="shipping_from toSelect2">
<option value="" selected="selected">-- SELECCIONAR --</option>
<option value="MRW">MRW - COBRO EN DESTINO</option>
<option value="DOMESA">DOMESA - COBRO EN DESTINO</option>
<option value="ZOOM">GRUPO ZOOM - COBRO EN DESTINO</option>
</select>
I need to remove the option MRW when checkbox .lives_in_ccs is checked so I made this code:
$(function () {
$('.toSelect2').select2();
var detachedMember;
$('.lives_in_ccs').click(function () {
if (this.checked) {
detachedMember = $('.shipping_from option[value="MRW"]').detach();
} else {
$('.shipping_from option[value=""]').after(detachedMember);
}
$(".secure_shipping").toggle(this.checked);
});
});
This code works but I'm having a problem and didn't found the way to fixit. Having this jsFiddle do this tests:
Leave the SELECT with the default value which is --SELECCIONAR-- and mark the check in the left side, that will works and will remove the option MRW from the main SELECT, if you unmark the check the value will appear again on the SELECT
Choose MRW (the first choice) on the SELECT and mark the check in the left side, that will remove the option MRW from the main SELECT, but will leave the option as SELECTED which is wrong since the server side isn't expecting it.
So, how do I remove the option even if it's selected on the SELECT element? Any help?

Here is the updated fiddle for testing: http://jsfiddle.net/fgaqgpd7/2/
This will reset the value of the select2 input:
$('.toSelect2').select2('val','');
You can apply it you click event handler. Basically if MRW is selected, then reset the select2 value.
$(function () {
$('.toSelect2').select2();
var detachedMember;
$('.lives_in_ccs').click(function () {
if (this.checked) {
if ($('.toSelect2').select2('val') == 'MRW') {
$('.toSelect2').select2('val','');
}
detachedMember = $('.shipping_from option[value="MRW"]').detach();
} else {
$('.shipping_from option[value=""]').after(detachedMember);
}
$(".secure_shipping").toggle(this.checked);
});
});

try this :
if($(".lives_in_ccs").is(':checked')){
$("#orders_shipping_from option[value='MRW']").remove();
}
Hope this helps :)

For me in version Select2 4.0.13:
$('#my-form').on('change', '.checkbox-item', updateDropdown);
HTML object:
<input type="checkbox" name="checkbox_1" id="checkbox_1" value="1" class="form-control checkbox-item" data-text="Label" />
Event function:
function updateDropdown(e) {
if (e.target.checked) {
if ($('#dropdown').select2('val') == $(this).val()) {
$('#dropdown').select2('val', '');
} else {
var newOption = new Option($(this).attr('data-text'), $(this).val(), false, false);
$('#dropdown').append(newOption).trigger('change');
}
} else {
$('#dropdown option[value="' + $(this).val() + '"]').detach();
}
}

Related

When one option is selected all others should be disabled

I have a dropdown menu that allows multiple selections. Now I want to make it when one particular option has selected all others to be disabled and enabled for selection. If that one particular is de-selected all others should be enabled again.
This is my select dropdown:
<select class="input-fields selectpicker" id="select_heigh" name="search[]" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>
And here is what I have tried for the js
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('.selectpicker').on('change', function() {
if ($('option[value="all"]', this).is(':selected') && $(this).val().length > 1) {
$('option[value="all"]', this).prop('selected', false);
$('.selectpicker').selectpicker('refresh');
}
var selected = $(this).val();
if (selected.includes("tag")) {
$('option[value!="tag"]', this).prop('disabled', true);
} else {
$('option[value!="tag"]', this).prop('disabled', false);
}
if (selected.length > 3) {
$(this).selectpicker('setStyle', 'selected-count', 'btn-danger');
$(this).selectpicker('setTitle', selected.length + ' select(s)');
} else {
$(this).selectpicker('setStyle', 'selected-count', 'btn-default');
$(this).selectpicker('setTitle', 'Select');
}
});
});
I want when "Tag" is selected the other options to be disabled. When "Tag" is de-selected the others are enabled. When any other option is selected to no effect on others.
Also, the counting of selected choices doesn't work as expected. It should start showing Selected(3), Selected(4) ... after the third selection. Currently, it shows all of them not count of them.
I'm not that familiar with JS and not sure if I'm on the right path here
What the OP wants to achieve is a rather unexpected behavior of a native form control.
And in case one changes the behavior it should be based on using what form elements or elements in particular do support natively like the disabled- and the dataset-property.
An implementation then could be as simple as querying the correct select element and subscribing an event listener to any click event which occurres on the very select element. The change event can not be used since any further changes are impossible once a single option is selected but all other option are disabled. An option element's dataset gets used as lookup in order to detect whether the very element already has been selected before the current click handling.
function handleOptionClickBehavior({ target }) {
const optionNode = target.closest('option');
const nodeValue = optionNode?.value;
if (nodeValue === 'tag') {
const optionNodeList = [...optionNode.parentNode.children]
.filter(node => node !== optionNode);
const { dataset } = optionNode;
if (dataset.hasOwnProperty('selectedBefore')) {
Reflect.deleteProperty(dataset, 'selectedBefore');
optionNode.selected = false;
optionNodeList
.forEach(node => node.disabled = false);
} else {
dataset.selectedBefore = '';
optionNodeList
.forEach(node => node.disabled = true);
}
}
}
document
.querySelector('.selectpicker')
.addEventListener('click', handleOptionClickBehavior)
body { zoom: 1.2 }
<select class="input-fields selectpicker" id="select_heigh" name="search[]" size="5" multiple>
<option value="all" selected>Search all</option>
<option value="tag">Tags</option>
<option value="username">Username</option>
<option value="email">Email</option>
<option value="full_name">Full Name</option>
</select>

How to trigger the change event on the input when I choose the option from select using jQuery?

I use jQuery to trigger an event in my project. I want to trigger an input event change when I choose an option from the select and when I choose an option the input value will be changed with the option value and show the length of the new value.
Also, I want to trigger an event change in the input but it does not work for me, I try many times but does not work :
$(document).ready(function() {
var oldVal;
var checkLength = function(val) {
$('label').html(val.length);
}
$('input').bind('change textInput input', function() {
var val = this.value;
if (val !== oldVal) {
oldVal = val;
checkLength(val);
}
});
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$("input").val(str);
})
});
This is how I would have done that.
Add change event listeners on both.
Update input with the value selected in select tag
Trigger change event from there
$("#s").change(function(){
console.log("Option selected");
$("#d").val($(this).val());
$("#d").trigger("change");
});
$("#d").change(function(){
console.log("input modified")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="d" />
<select id="s">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Try manually triggering the change event of input like this
*$( "input" ).trigger("change");*

Select Drop down Form Validation (Display text)

I am trying to validate a form.
What I am trying to do is validate the form by validating the Option display text not the option value, since the option values are int
Example:
<option value="selectcard">Please select</option>
If user clicks submit the form should validate if the option display says Please Select
regardless of what the option value is.
Code which is not working
function fun(){
$('#cardtype').change(function () {
var sel = $('option:selected', this).text();
if (sel == "Please select") {
$('.showotherpDescription').show();
} else {
}
});
}
Not working: http://jsfiddle.net/f5hxpo7g/2/
Also including the regular working example for validating the form based on option value
Validates Based on option value http://jsfiddle.net/f5hxpo7g/1/
Please let me know what i am doing wrong.
Thanks in advance.
Your function should be like this:
function fun()
{
var ddl = document.getElementById("cardtype");
var valor = ddl.options[ddl.selectedIndex].text;
if (valor == "--- Please select ---")
{
alert("Please select a card type");
}
}
Working fiddle:http://jsfiddle.net/robertrozas/XFtBD/169/
I fixed it, you should use this JS:
$(function () {
$('#subbutton').click(function () {
if ($('#cardtype option:selected').text() === "Please select")
{
alert("PLEASE SELECT");
}
});
});
And remove onclick="..." from the button, you don't need it. Also add id="subbutton.
Here's the working JSFiddle.
I checked out the jsfiddle you referenced and modified it slightly to make it work, you can see it here.
The issue with the code you provided is, IMO:
An issue with the purpose of your function (validation) and the event you're subscribing the code to (the combo selection changed event)
The way you're obtaining the text from the currently selected option, you should create the selector based on the element that contains the options, otherwise, if you have more than 1 combo in your page, you will get lots of values (one for each selected option).
Check out the code in the jsfiddle i provided and let me know if you need more information.
For reference, here is the code i used:
HTML:
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select>
<input type="button" onclick="fun()" value="click here">
JS:
function fun(){
var cmb = document.getElementById('cardtype');
var sel = cmb.options[cmb.selectedIndex].text;
if (sel == "--- Please select ---") {
alert('Please select a different option');
//$('.showotherpDescription').show();
} else {
}
}
}

How to update a textarea's text relative to a checked radio button?

A textarea's text will be populated with a dropdown lists selected
text.
A simple radio button list will determine which dropdown list's text should be used.
CLICK HERE FOR DEMO
The code below creates the desired effect but does not make the expected changes when an alternate radio button value is selected.
Debugging shows checked is not added to radio inputs when a new selection is made.
JQUERY
var rbl = $('#rbl input:checked').val();
$('#ddlA1,#ddlB1').change(function () {
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
HTML
<span id="rbl">
<input type="radio" id="rbl_0" name="rbl" value="1" /> 1 <br />
<input type="radio" id="rbl_1" name="rbl" value="2" /> 2 <br />
</span>
<select id="ddlA1">
<option value="1">A1 A</option>
<option value="2">A1 B</option>
<option value="3">A1 C</option>
</select>
<select id="ddlB1">
<option value="1">B1 A</option>
<option value="2">B1 B</option>
<option value="3">B1 C</option>
</select>
<textarea id="txt">LOAD TEXT</textarea>
Your code is correct but you need to modify some little things ;)
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl == 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl == 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});
Put rbl variable inside the change event
Use == instead of = on your conditionals
http://jsfiddle.net/3kXsX/5/
That's all!
Best Regards,
Something more like this
$('#rbl_0, #rbl_1, #ddlA1, #ddlB1').on('change', function() {
var dropdown = $($('#rbl_0').is(':checked') ? '#ddlA1' : '#ddlB1');
$('#txt').val(dropdown.find('option:selected').text());
});
FIDDLE
The value of rbl is set once, when that line of code runs, and not updated if the selected radio changes. Put the var rbl = ... line inside the event handler so it checks the radios when a change is made to the dropdown, ie
$('#ddlA1,#ddlB1').change(function () {
var rbl = $('#rbl input:checked').val();
if (rbl = 1) {
$('#txt').val($('#ddlA1 :selected').text());
} else if (rbl = 2) {
$('#txt').val($('#ddlB1 :selected').text());
}
});

jquery change function hide and show div

have this code, i want to convert it to be able to allow the user to pick ANY possible select and have div [id='setprice'] show up or something to that effect. currently i have 4 options, but it could be up to 10+ depends on how many are in the database. but it shouldn't matter, i just want which ever gets selected to open the setprice div. Thanks.
$("#category").change(function () {
$("#setprice").hide();
if ($(this).val() == "cow") { $("[id='setprice']").show(); }
else if ($(this).val() == "dog") { $("[id='setprice']").show(); }
else if ($(this).val() == "monkey") { $("[id='setprice']").show(); }
else if ($(this).val() == "kungfoo") { $("[id='setprice']").show(); }
});
HTML
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice'>this is hidden onload, then shows on any #category selection</div>
Seems to be alot of cofusion in what im asking, These options i've given are random names, the categories that are going to be loaded, are from a database and more could be added depending how it expands, so i want the script to not show div=setprice, but when anything gets selected in #category to open setprice.
You will need to call the function only when the value of the select box isn't empty.
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
Here is a working fiddle.
This is the cleanest you will get this.
DEMO
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
The $("#setprice").toggle(!!this.value); is just a way to use a boolean inside the .toggle() method,
otherwise you do it equally like:
var $setPriceEl = $("#setprice");
$("#category").change(function () {
$setPriceEl.hide(); // hide by default
if(this.value) $setPriceEl.show(); // show only if has value
});
or even:
$("#category").change(function () {
$("#setprice")[this.value ? "show" : "hide" ]();
});
Please find the answer below ...
HTML :
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice' style="display:none;">this is hidden onload,
then shows on any #category selection</div>
JQUERY :
$(document).ready(function(){
$("#category").change(function() {
$("#category option:selected" ).each(function() {
var str = $( this ).text();
if(str == "Select"){
$("#setprice").hide();
}else{
$("#setprice").show();
$("#setprice").text(str);
}
});
}).trigger("change");
});

Categories