jquery programmatically reselecting multselect does not reselect - javascript

I am trying to select all options in a multselect with a tickbox using jquery 2.1.1.
This works fine on the first tickbox select and deselect, however subsequent selects of the tickbox do not highlight the multiselect options and the change event writing to console displays null for the values.
Below is a working copy that can be cut and paste to a file to illustrate the problem - naturally I've searched stack overflow for this issue but can't find it listed.
Any idea why a reselecting the tickbox adds 'selected = "selected" but does not highlight the options and results in 'null' for the values in the console?
I appreciate any help.
jQuery(document).ready(function($) {
jQuery(function() {
jQuery('#bundle-option-5').change(function() {
console.log(jQuery(this).val());
});
});
});
function updateBundleItems(bundleOptionId) {
if (jQuery('input#bundle_tick_' + bundleOptionId).is(':checked')) {
//jQuery('.bundle_item_'+bundleOptionId).addAttr("selected");
jQuery('.bundle_item_' + bundleOptionId).attr('selected', true);
} else {
// jQuery('.bundle_item_'+bundleOptionId).removeAttr("selected");
jQuery('.bundle_item_' + bundleOptionId).attr('selected', false);
}
jQuery('#bundle-option-' + bundleOptionId).trigger('change');
}
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="input-box">
<input class="checkbox" onclick="updateBundleItems(5)" id="bundle_tick_5" type="checkbox">
<select multiple="multiple" size="5" id="bundle-option-5">
<option value="">None</option>
<option class="bundle_item_5" value="11">first one</option>
<option class="bundle_item_5" value="12">second one</option>
<option class="bundle_item_5" value="13">third one</option>
</select>
</div>

You should use the prop function instead of the attr one.
Here is the change in your code:
jQuery(document).ready(function($) {
jQuery(function() {
jQuery('#bundle-option-5').change(function() {
console.log(jQuery(this).val());
});
});
});
function updateBundleItems(bundleOptionId) {
if (jQuery('input#bundle_tick_'+bundleOptionId).is(':checked')) {
//jQuery('.bundle_item_'+bundleOptionId).addAttr("selected");
jQuery('.bundle_item_'+bundleOptionId).prop('selected', true);
}
else {
// jQuery('.bundle_item_'+bundleOptionId).removeAttr("selected");
jQuery('.bundle_item_'+bundleOptionId).prop('selected', false);
}
jQuery('#bundle-option-'+bundleOptionId).trigger('change');
}
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="input-box">
<input class="checkbox" onclick="updateBundleItems(5)" id="bundle_tick_5" type="checkbox">
<select multiple="multiple" size="5" id="bundle-option-5">
<option value="">None</option>
<option class="bundle_item_5" value="11">first one</option>
<option class="bundle_item_5" value="12">second one</option>
<option class="bundle_item_5" value="13">third one</option>
</select>
</div>

Related

using jQuery to get selected value from form

I have a form that has a select field defined like this
The myName[] is like that because there are several repetitions in the sign-up form (the user first defines how many he wants to enter, and then that many forms are generated)
Now I would like to get the selected value using jQuery whenever somethign is selected, but as expected, it won't work: it's trying to get the info from an id, and there's more than one of this id. The result is that it's always getting the content of the first select field with the id it finds. I tried changing the id to a class, but that didn't work.
So how can I get the selected value of the select box that's actually triggering the event?
$(document).ready(function() {
$('#idOfmyName').change(function() {
var naam = $(this).find("option:selected").attr('value');
alert(naam);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="myname[]" id="idOfmyName">
<option value="jack">Jack</option>
<option value="rose">Rose</option>
</select>
Why can't you just use $(this).val(), if you want the selected Element?
But yes, when you've got multiple of the same ID, jQuery will over ever select the first one it finds - Though you do seem to know this; I've changed it to a class in this demo
$(document).ready(function() {
$('.idOfmyName').on('change', function() {
alert($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="myname[]" class="idOfmyName">
<option value="jack">Jack</option>
<option value="rose">Rose</option>
</select>
<select name="myname[]" class="idOfmyName">
<option value="harry">Harry</option>
<option value="sally">Sally</option>
</select>
<select name="myname[]" class="idOfmyName">
<option value="edward">Edward </option>
<option value="vivian">Vivian </option>
</select>
for multiple you can do something like this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="myname[]" class="idOfmyName">
<option value="jack">Jack</option>
<option value="rose">Rose</option>
</select>
<select name="myname[]" class="idOfmyName">
<option value="jack">Jack</option>
<option value="rose">Rose</option>
</select>
<script>
$(document).ready(function() {
var names = [];
$('.idOfmyName').change(function() {
var naam = $(this).find("option:selected").attr('value');
if($.inArray(naam,names)){
names.push(naam);
}
alert(names);
});
});
</script>
Vanilla JavaScript way to get selected value using onchange method
function getSelectedValue(val) {
alert(val);
}
<select name="myname[]" onchange="getSelectedValue(this.value)">
<option value="jack">Jack</option>
<option value="rose">Rose</option>
</select>
<select name="myname[]" onchange="getSelectedValue(this.value)">
<option value="harry">Harry</option>
<option value="sally">Sally</option>
</select>

How to Select Dropdown hidden option with Jquery Selector?

<select class="form-control" id="prodname" name="pname" >
<option value="0" disabled="disabled" selected="selected">-- Select Product --</option>
#{
foreach(var product in (List<tbleProdcutDetail>)ViewBag.productlist)
{
<option value="#product.Id">#product.Product_Name</option>
<option hidden>#product.Quantity</option>
}
}
</select>
I want to select this option.
<option hidden>#product.Quantity</option>
I have tried this selector but could not get text.
var productunitprice = $("#prodname option").find("hidden").text();
You can use var text = $("option:selected",this).next().text() Example below.
$("#prodname").change(function() {
var text = $("option:selected",this).next().text()
console.log(text)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="prodname">
<option value="1">1</option>
<option hidden>1.1</option>
<option value="2">2</option>
<option hidden>2.2</option>
</select>
As an alternative to adding many unused and hidden options.
You can add the unit price to the relevant option directly using a data attribute for example data-unit-price.
foreach(var product in (List<tbleProdcutDetail>)ViewBag.productlist)
{
<option value="#product.Id" data-unit-price="#product.Quantity">#product.Product_Name</option>
}
Then simply read it from the selected option. In my humble opinion it is cleaner and doesn't use additional hidden option elements as storage for data belonging to other options.
$(document).ready(function() {
$("#prodname").change(function() {
var productunitprice = $("option:selected", this).data('unitPrice')
console.log(productunitprice)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="prodname" name="pname">
<option value="1" data-unit-price="5.25">product 45</option>
<option value="2" data-unit-price="12.99">product 94</option>
</select>

What event can I bind on an option in a select multiple?

Assuming I have a multiple select list like:
<select name="persons" id="persons" multiple size="8">
<option id="captureMe">Test option</option>
<option value="" disabled="disabled">─────────</option>
<option value="FR">Franck</option>
<option value="GE">Georges</option>
<option value="DA">David</option>
<option value="LU">Luc</option>
<option value="DO">Donald</option>
<option value="FR">FRANCOIS</option>
</select>
What event can I bind on $("#captureMe") ?
I tried some scripts like
$("#captureMe").change(function() {alert("got it!");});
$("#captureMe").on("change", function() {alert("got it!");});
$("#persons").on("change", "#captureMe", function() {alert("got it!");});
But none of these works nor with the click event.
So my question is, what event can I bind to an option in a select multiple ?
I don't wont the event being fired from the select but from the option by itself
(The goal could be firing an ajax call when a specific option is changed)
You can use click event instead of change:
$("#captureMe").on('click', function(){
console.log("got it!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="persons" id="persons" multiple size="8">
<option id="captureMe">Test option</option>
<option value="" disabled="disabled">─────────</option>
<option value="FR">Franck</option>
<option value="GE">Georges</option>
<option value="DA">David</option>
<option value="LU">Luc</option>
<option value="DO">Donald</option>
<option value="FR">FRANCOIS</option>
</select>
Please, take a look to the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<select name="persons" id="persons" multiple size="8">
<option id="captureMe">Test option</option>
<option value="" disabled="disabled">─────────</option>
<option value="FR">Franck</option>
<option value="GE">Georges</option>
<option value="DA">David</option>
<option value="LU">Luc</option>
<option value="DO">Donald</option>
<option value="FR">FRANCOIS</option>
</select>
</body>
<script>
$("#persons").change(function() {
var values = $("#persons").val();
if($.inArray($("#captureMe").val(), values) > -1){
if(!$("#captureMe").prop("isSelected")){
$("#captureMe").prop("isSelected", true);
console.log("'caputreMe' is selected");
}
}else{
if($("#captureMe").prop("isSelected")){
$("#captureMe").prop("isSelected", false);
console.log("'caputreMe' is unselected");
}
}
});
</script>
</html>
I hope it helps you. Bye.
$(document).on("change", "#persons", function() {alert("got it!");});
You can for example use the :selected selector, see https://api.jquery.com/selected-selector/
$("select").change(function() {
$("#captured-by-id:selected").each(function() {
alert($(this).text());
});
});
Here's a Fiddle.
isn't it possible to make it work in following way?
var selectedValue = "";
$("#persons").change(function() {
var values = $(this).val();
if()// condition to check if #captureme option is present in "selectedValue" variable
{
// logic
}
else if() // condition to check if #captureme was not present in "selectedValue" before and is selected now
{
// logic
}
selectedValue = value;
});

I need to trigger change function whenever a text in dropdown list is selected

My jquery code is having two dropdown boxes,one containing country and the other one holds currency.so here i want that whenever a country is selected in the box it will trigger a change function that will perform some comparison using if-else and will select the currency in the other dropdown and leaving it as 'disabled' to true.Below is my code for the same:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(".select").change(function () {
debugger;
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').attr("selected", true);
document.getElementById('disable').disabled = true;
}
else
{
$('select[name="currency"]').find('option[value="2"]').attr("selected", true);
document.getElementById('disable').disabled = true;
}
});
});
//$(function () {
// var select = $('select.select');
// select.change(function () {
// select.not(this).val(this.value);
// document.getElementById("disable").disabled = true;
// });
//});
</script>
</head>
<body>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency" id="disable" class="select">
<option value="">Select</option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
<br><br>
</form>
</body>
</html>
but now the problem is when i select india it shows IR which is ok and then when i select America,it shows Doller and finally the problem comes now,when i again change the country back to india the change function is not called at all and dollar gets remain selected and disabled.Fix this it would be a great help!
Use .prop instead of .attr
With .attr, both the options have selected attribute set hence browser fail to make out which option to be set as selected.
From docs, To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method. (.attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior.)
$(document).ready(function() {
$(".select").change(function() {
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').prop("selected", true);
} else {
$('select[name="currency"]').find('option[value="2"]').prop("selected", true);
}
document.getElementById('disable').disabled = true;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency" id="disable" class="select">
<option value="">Select</option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
<br>
<br>
</form>
Since the values on both select are the same. You can easily set the value of the second select based on the first.
$(function() {
$('.select').on('change',function() {
var val = $(this).find(':selected').val();
$('[name=currency]').val( val ).attr('disabled',true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select name="country" id="country" class="select">
<option value="">Select</option>
<option value="1">india</option>
<option value="2">America</option>
</select>
<select name="currency">
<option value=""> </option>
<option value="1">INR</option>
<option value="2">DOLLAR</option>
</select>
</form>
To complete the above answer you can use the "$" jquery selector instead of document.getElementById
Plus note you can use .prop('disabled', false);
too, like this :
$(document).ready(function() {
$(".select").change(function() {
var c = $('#country :selected').text();
if (c == 'india') {
$('select[name="currency"]').find('option[value="1"]').prop("selected", true);
} else {
$('select[name="currency"]').find('option[value="2"]').prop("selected", true);
}
$(#'disable').prop('disabled', true);
});
});

Jquery/Js: Hide/Show Divs based on select box option values

These are Dynamic dependent select controls. The sets of values of (1-3, 4-6, 7-9) determine the use hide/show divs function. The problem is the function i have only hide/show depending on the div id. How can i make the function hide/show div depended on the values(1-3, 4-6, 7-9) found in the selectbox?
Jquery
$('#select').change(function() {
$('#sub1, #sub2, #sub3').hide();
$('#sub' + $(this).find('option:selected').attr('id')).show();
});
Html Setup
<html>
<select size="6" id="category">
<option value="">categories 1-3 </option>
<option value="">----</option>
<option value="">----</option>
</select>
<div id="sub1" style="display:none">
<select name="subc1" size="6">
<option value="1">subcategories 4-6</option>
<option value="2">---</option>
<option value="3">---</option>
</select>
</div>
<div id="sub2" style="display:none">
<select name="subc2" size="6">
<option value="4">subcategories 7-9</option>
<option value="5">----</option>
<option value="6">----</option>
</select>
</div>
<div id="sub3" style="display:none">
<select name="subc3" size="6">
<option value="7">End</option>
<option value="8">----</option>
<option value="9">----</option>
</select>
</div>
</html>
select the value from drop down change function and do the operation depends on the value of drop down, following is the sample code
$(function() // Shorthand for $(document).ready(function() {
$('select').change(function() {
if($(this).val() == 1)
{
$('#sub1').hide();
$('#sub2').show();
}
});
});
You nee to change minor change in your category select
<select size="6" id="category">
<option value="1">categories 1-3 </option>
<option value="2">----</option>
<option value="3">----</option>
</select>
$('select#category').on('change', function() {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
});
can also use .change() instead of .on('change').
$('select#category').change(function() {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
});
NOTE:
$('div[id=^sub]:visible') will point to all divs that have id start with sub and visible.
You are trying with $('#select') which need to be $('#category') or $('select#category').
According to your comment:
Complete solution will look like following:
function isOnlyDashed(text) {
return text.replace(/-/g, '').length === 0;
}
$('select#category').change(function() {
var text = $('option:selected', this).text();
if (!isOnlyDashed(text)) {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
}
});
$('select[name^=subc]').change(function() {
var text = $('option:selected', this).text();
if (!isOnlyDashed(text)) {
$(this).parent() // jump to parent div
.next('div[id^=sub]:hidden') // go to next hidden div
.show();
}
});
Complete Workout
The problem with your code is that you have an incorrect selector.
$('#select')...
should be
$('select')...
Also, this part is wrong
$('#sub' + $(this).find('option:selected').attr('id')).show();
Replace it with this
$('#sub' + $(this).val()).show();
Finally, having different elements with the same name/id "sub1" is probably a bad idea, though technically not illegal. It is certainly confusing.
working demo http://jsfiddle.net/FwBb2/1/
I have made minor changes in your Jquery code as well as added value in your first select drop-down list which was missing rest hope this helps.
Please lemme know if I missed anything! B-)
code
$('select').change(function() {
$('#sub1, #sub2, #sub3').hide();
$('#sub' + $(this).val()).show();
});​
HTML
<html>
<select id="category">
<option value="1">categories 1-3 </option>
<option value="2">----</option>
<option value="3">----</option>
</select>
<div id="sub1" style="display:none">
<select name="subc1" size="6">
<option value="1">subcategories 4-6</option>
<option value="2">---</option>
<option value="3">---</option>
</select>
</div>
<div id="sub2" style="display:none">
<select name="subc2" size="6">
<option value="4">subcategories 7-9</option>
<option value="5">----</option>
<option value="6">----</option>
</select>
</div>
<div id="sub3" style="display:none">
<select name="subc3" size="6">
<option value="7">End</option>
<option value="8">----</option>
<option value="9">----</option>
</select>
</div>
</html>​

Categories