Jquery select variable by id - javascript

I am trying to get the content of a select option which is specified by the selected options.
I can get the selected options to tell me the data-parent but I can't use that to get the text of the parent option.
<select id="addCatSelectCats" multiple="multiple">
<option id="Cat55" data-parent="5">Parent Cat</option>
<option id="Cat357" data-parent="55">Sub Cat</option>
</select>
$(document).on('change', '#addCatSelectCats',function() {
$("#addCatSelectCats option").each(function(){
if($(this).is(':selected')){
var dataparent = $(this).attr('data-parent');
if(dataparent > 0){
var parent = $('#Cat'+dataparent).text();
alert(parent);
}
}
});
});
Where am I going wrong?

You could do with a little less code
$(document).on('change', '#addCatSelectCats',function() {
var parent = $("#addCatSelectCats option:selected").text();
alert(parent);
});

Related

How To Get Selected Value When <select> </select> changed Using JS

I am stuck & want to get selected the select option.
<select class="form-control" data-live-search="true" id="itemb">
<option data-tokens="All">All</option>
#foreach (var item in ViewBag.brandCategories)
{
<option>#item.brandName</option>
}
</select>
//search by brand name..
$("#itemb").change(function () {
var typp = document.getElementById("typ").value;
var type = encodeURIComponent(typp);
var brand = this.value;
window.location.href = '/mobiles_tablets/item/?type=' + type + '&search=' + brand;
});
In the above code just i get list in #foreach through #viewBag .but now I want when it return to the view it should get selected value.
please write js code?
Thanks.
This snippet of code will help you to get the selected value of select element. You can modify/change it through codepen check out the below link.
https://codepen.io/uicreation/pen/KZmXbw
var el = document.getElementById('yourId');
el.onchange = function(){
console.log(this.selectedOptions[0].value);
}
<select id="yourId">
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
or if you want to get selected option index use this.
var el = document.getElementById('yourId');
el.onchange = function(){
console.log(this.selectedIndex);
}

Setting the first value as default in dropdown list

Jquery to create new row :
var selectVal = $(parent).children().first().find('select').find('option[selectedGivenTo="true"]').val();
var newSelect = $(parent).children().last().find('select');
newSelect.each(function() {
var cloned = null;
cloned = $(this).clone();
cloned.val(selectVal);
I am trying to select the first value of dropdownlist as default value using jQuery as above but no value is selected & just displaying list in dropdown.I saw many references in stackoverflow but its not working for me.
HTML:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
jQuery:
$(function(){
$("select option:first").attr('selected','selected');
var _select = $('select')[0],
_v = _select.options[_select.selectedIndex].value;
alert(_v);
});
Demo
If you want to select it by value, then use the code below:
$('select option[value="defaultValue"]').attr("selected",true);
If you want to select via text contains in option, use the following code:
$('select option:contains("I am defualt Value")').prop('selected',true);

Using a variable as JQuery selector

I have a dropdown/select menu that shows and hides various divs based on what the user has selected. Within each div there is another dropdown/select menu that I would like to also trigger an action on change.
As this div is given an ID dynamically I am struggling to figure out how to select the required dropdown/select menu.
Here is the jQuery code:
$(document).ready(function(){
$("#category").change(function(){
var category = $("#category").val();
var box = $('#'+ category);
$('.class-name').hide();
box.show();
}) ;
var category = $("#category").val();
var selector = 'selector_'+category;
$("#"+selector).change(function(){
alert('Do something');
});
});
And some simplified HTML:
<select id='category'>
<option value='0'>1</option>
<option value='1'>2</option>
<option value='2'>3</option>
</select>
<div class='box class-name' id='1'>
<select id='selector_1'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
</div>
<div class='box class-name' id='2'>
<select id='selector_2'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
</div>
<div class='box class-name' id='3'>
<select id='selector_3'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
</div>
The divs show and hide as desired, but I can't for the life of me get the alert('Do Something'); to trigger which I assume is a problem with how I am trying to select the dropdown/select menu.
All help much appreciated!
Cheers, DB.
You need chain the changes. The way you made it, the code runs all at once, meaning:
When document ready, do:
Set onChange in the #category element
Find category current value (right now, none is selected, so value is undefined)
Set selector to "selector_" + undefined
Find element with id selector, since there's no element with this id, no change is defined.
Try this, instead:
$(document).ready(function() {
var categoryField = $("#category");
categoryField.change(function() {
var category = categoryField.val();
var box = $('#'+ category);
$('.class-name').hide();
box.show();
var selector = 'selector_'+category;
$("#"+selector).change(function() {
alert('Do something');
});
});
});
var category = $("#category").val();
Category is empty on page loaded.
Simple solution:
$(".box select").change(function(){
alert('Do something');
});
I checked, it's working
$("#category").change(function(){
var category = $("#category").val();
var box = $('#'+ category);
$('.class-name').hide();
box.show();
var s = $(box).find('select');
$(s).bind("change", function() {
alert("Do something");
})
})
Within each div there is another dropdown/select menu that I would
like to also trigger an action on change.
It seems you are looking to trigger event when there is a change in the dropdowns wrapped by the div
If it is so you can use jquery wild card selector
In your case all those select elements have same prefix id.
So $("[id^=selector_]") will response to to any select box which have such string as prefix
$("[id^=selector_").change(function(event){
$("#demoUp").text($(this).context.value);
});
Check this JSFIDDLE. The placeholder will be updated by the value of selectd option
To point you have change the id on document page ,use below
$(document).on("change",$("#"+selector),function(){
alert('Do something');
});
Try this:
$(document).ready(function(){
$("#category").change(function(){
var category = $(this).val();
$('.class-name').hide();
$('#'+ category).show();
$("#selector_"+category).change(function(){
alert('Do something');
});
}) ;
});

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

verify all elements in a class

I have a form that has a handful of dropdowns. I want to confirm all dropdowns have been selected before form submit. The id's of the elements are variable so i cant use them as a selector, so i put all the elements in the verify class. So now i need to iterate through all elements that have the verify class and make sure they are not empty/undefined/null. the number of elements is unknown as well. I am guessing I would map or use each on some level, I just don't know where to begin.
$('.verify').change(function()
{
//iterate through each item with verify class..
if (//All items are selected)
{
$(":button:contains('Complete')").removeAttr("disabled").removeClass('ui-state-disabled' );
}
});
html:
<td class='dialog'>
<select id='someVariable' class='verify'>
<option value=''></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</td>
<td class='dialog'>
<select id='someOtherVariable' class='verify'>
<option value=''></option>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
</td>
Try
var $varifies = $('.verify').change(function () {
//iterate through each item with verify class..
var invalid = $varifies.filter(function () {
return !$(this).val();
}).length;
$(":button:contains('Complete')").prop("disabled", invalid);
});
Demo: Fiddle
i suggest $('.verify').not('[value!=""]').length == 0
First select the elements which are having selected options in it. and compare its length with the overall count of select elements. If counts are same, All elements have been selected.
Try,
var $varifies = $('.verify').change(function () {
var xSelectedElems = $('.verify').filter(function () {
return $(this).find('option:selected').val() != '';
}).length;
var xTotalElems = $('.verify').length;
$(":button:contains('Complete')").prop("disabled", (xTotalElems != xSelectedElems));
});
DEMO
You might be over complicating it a little. On submit, loop over each select.verify element and check its value propery:
$($(".verify:first")[0].form).submit(function(event) {
var valid = true, $form = $(this);
$form.find(".verify").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
$(this).addClass("ui-state-invalid");
}
else {
$(this).removeClass("ui-state-invalid");
}
});
if (valid) {
$form
.find(":button:contains('Complete')")
.removeAttr("disabled")
.removeClass('ui-state-disabled');
}
else {
event.preventDefault();
}
});

Categories