jQuery each function $(this) confusion - javascript

EXPLANATION:
I have two element with as many options inside them.
the first contains a series of options which have their db-id as their values. these are parents.
the second element is populated with a list of options which have their parent db-ids as their values and their own db-ids as their html id-attribute. these are children categories.
PROBLEM:
I want to have all the children cats to be hidden, and on each select event of any parent category, the relative children to become visible, using their values which is identical to their parent's value.
MY ATTEMPTS:
For this purpose, I have written the following script which does not work. It attaches a click event to each parent category, and this event triggers a function which is responsible to turn the visibility of any child cat on, if their values matches the values of the clicked element.
HTML CODE:
<select multiple name="branch" >
<option selected="" value="false">Please Select a Branch</option>
<option class="branch-item" value="0">Computer</option>
<option class="branch-item" value="1">Automobile</option>
<option class="branch-item" value="4">Technical</option>
</select>
<select multiple class="form-option" name="subbranch" >
<option class="subbranch-item" style="display: none;" value="1">Software</option>
<option class="subbranch-item" style="display: none;" value="1">Hardware</option>
<option class="subbranch-item" style="display: none;" value="7">Mechanics</option>
<option class="subbranch-item" style="display: none;" value="7">Welding</option>
</select>
JQUERY CODE:
<script type="text/javascript">
$(document).ready(function(e) {
$(".branche-item").click(function(){
var values = $(this).val();
$('.subbranch-item').parent().each(function(element, value) {
if(value == values)
{
element.show();
}
});
});
});
</script>
I appreciate any help on the debugging of the jquery code, thanks

Try
var $sub = $('select[name="subbranch"]');
var sub = $.trim($sub.html());
$('select[name="branch"]').change(function () {
var filter = $(this).children('option:selected').map(function () {
return '[value="' + this.value + '"]'
}).get().join();
$sub.empty().append($(sub).filter(filter))
}).change()
Demo: Fiddle

$('select[name="branch"]').change(function () {
var $branch = $(this).children(':selected'),
$subbranch = $('[name="subbranch"]').children('option');
$subbranch.hide()
$branch.each(function () {
var branch = $(this).val();
$subbranch.each(function () {
if ($(this).val() == branch) {
$(this).show();
}
});
});
}).change();
http://jsfiddle.net/F9777/3/

Related

Get selected item on select with js

Look, i'm getting crazy, i can't get the selected item inside a normal select dropdown list (The values of the list are created dynamiclly with js).
I have a list of items and that are the columns of a table and i want when i click on an item, the column is added to the table and if i click another time in that item the column is removed.
I've tried to use a change event with jquery and onchange event with js but if i select the item two times in a row the column is added but not removed because the value hasn't changed.
I've tried to give a onclick event to the options of the select but nothing happens when i click on one. I've tried to capturo the clicked option from the select with jquery with this code:
$("#selectTableLt").on("click", "option", function() {
let clickedOption = $(this);
console.log(clickedOption);
});
But nothing happens.
Can anyone help me with this, please? Thank you
Edit:
My html:
<select name="leftColumns" id="selectTableLt"></select>
I load the options with javascript but they look like:
<option value="opt1">Option 1</option>
It's very simple
Check this out
<!DOCTYPE html>
<html>
<head>
<title>Select from dropdown list</title>
</head>
<body>
<h1>Select from dropdown list</h1>
<p id="result">Result here</p>
<select id="country">
<option value="None">-- Select --</option>
<option value="ID1">America</option>
<option value="ID2" selected>India </option>
<option value="ID3">England</option>
</select>
<script>
function GetSelectedValue(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].value;
document.getElementById("result").innerHTML = result;
}
function GetSelectedText(){
var e = document.getElementById("country");
var result = e.options[e.selectedIndex].text;
document.getElementById("result").innerHTML = result;
}
</script>
<br/>
<br/>
<button type="button" onclick="GetSelectedValue()">Get Selected Value</button>
<button type="button" onclick="GetSelectedText()">Get Selected Text</button>
</body>
</html>
here is a solution to handle the multiple click events and fetch the dropdown selected value
var oldValue = null;
$(document).on("click","#selectTableLt", function(){
s = $(this);
val = s.val();
if (oldValue == null) {
oldValue = val;
} else {
var newValue = s.val();
if (newValue != "") {
var finalVal = oldValue == s.val() ? oldValue : newValue;
console.log(finalVal)
}
$(document).unbind('click.valueCheck');
oldValue = null;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
You need to fetch the value using $.val() function
bind event to document in order to handle the dynamic event listener
$(document).on( eventName, selector, function(){} );
Using the Change Event:
$(document).on("change","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>
Using the Click Event:
$(document).on("click","#selectTableLt", function() {
let clickedOption = $(this).val();
console.log(clickedOption);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectTableLt">
<option value="0">One</option>
<option value="1">Two</option>
</select>

How do I show a message for a specific dropdown selection using javascript?

I would like to show a message when someone makes a specific selection from an HTML dropdown list. I have this so far:
<select name="configoption[56]" onchange="recalctotals()">
<option value="235"">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
And the script:
$(document).ready(function() {
$('#configoption[56]').change(function() {
var selectedValue = $('#configoption[56]').find(":selected").text();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
The above does not appear to be working for me, any suggestions? I would also like to be able to show the message on multiple selected values.
Well your .change function is specifically binded to an element with id="configoption[56]" So just add id to your select element as below
<select name="configoption[56]" id="configoption[56]" onchange="recalctotals()">
//Options
</select>
UPDATE
As per #T.J.Crowder's suggestion on invalid selector I would like to modify a slight change on the id. You can use configoption56 as id and write your select.change as follows:
<select name="configoption[56]" id="configoption56" onchange="recalctotals()">
<!--Options-->
</select>
.change
$('#configoption56').change(function() {
//other codes
});
$('#configoption[56]') is looking for an element with the id, not name, configoption[56] (or it would be, but the selector is invalid, you'd have to escape those brackets).
To use the name:
$('select[name="configoption[56]"]')...
Separately, you can just use val, you don't have to use find to get the selected option. You can also use toggle for show/hide:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
$('.message').toggle($(this).val() == '235');
});
});
Re your comment about toggling based on || and two values:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
var value = $(this).val();
$('.message').toggle(value == '235' || value == '123');
});
});
I should be doing it like this: http://jsfiddle.net/nmn17cr6/
HTML:
<select name="configoption[56]" id="configoption" onchange="recalctotals()">
<option value="1">Dummy</option>
<option value="235">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
CSS:
.message {
display:none;
}
jQuery:
$(document).ready(function() {
$('#configoption').change(function() {
var selectedValue = $(this).val();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
Your approach needs a little modification. All you had to do these changes
$(document).ready(function() {
$("select[name=configoption[56]]").change(function() { // change jquery selector for name
var selectedValue = $('#configoption[56]').val(); // and val to get the value
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
And with the same jQuery code. below has to be
<select name="configoption[56]" >
// onchange="recalctotals()"> was not required

Get Option HTML by it's value in Jquery

How we can get the option HTML in jquery by it's value in jQuery.
HTML
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
Array
var id_arry = ['21','24','2'];
I have this array that have some values related to values in the drop down. Now i want to get all the options that matches the value in dropdown HTML
like
<option value="21">A</option><option value="24">D</option> <option value="2">E</option>
This is the final out put i want from the drop-down.Kindly help me in this
I want to add those options html in this dropdown:
<select multiple="" style="width: 147px;" id="list" name="list1" class="list_class">
</select>
Maybe something like this:
var id_arry = ['21','24','2'];
var optionMatches = $('#list option').filter(function() {
return $.inArray($(this).val(), id_arry);
});
Breaking it down:
$('#list option') - returns all of the options in the select list with ID "list"
.filter(callback) - a simple filter function -- the callback decides whether the option makes it into the final list
$.inArray($(this).val(), id_arry) - checks if the current option value is in the array id_arry
After studying your example, it looks like you'll first want to obtain the selected options from your multi-select drop-down list to build your id_arry, which is very easy:
var id_arry = $('#list').val();
Once you have these and the optionMatches array of elements, you can clone them over to a new drop-down:
optionMatches.clone().appendTo('#otherSelect');
One solution is using join and split:
var id_arry = ['21', '24', '2'];
$("#list").val(id_arry.join(',').split(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" style="width: 147px;" id="list" name="list" class="list_class">
<option value="21">A</option>
<option value="22">B</option>
<option value="23">C</option>
<option value="24">D</option>
<option value="2">E</option>
</select>
You can use jQuery's attribute equals selector to target elements with a specific attribute value:
$( "option[value='21']" )
Using this selector and a simple loop, you can extract all the elements you need:
var elements = [];
var id_array = ['21','24','2'];
for ( index in id_array ){
var elem = $( "option[value='" + id_array[ index ] + "']" );
if ( elem ) {
elements.push( elem );
}
}
Your elements array now contains all option elements who's values appear in id_array.
var id_arr = ['21','24','2'];
var entireHTML = "";
var options = $('select').find('option');
var tempDiv = $('div');
//id_arr = $('select').val(); //Uncomment this line to get value from the select element.
$.each(id_arr, function(index, value){
entireHTML = "";
$(options).each(function(){
if( $(this).val() === value)
{
$(this).clone().appendTo(tempDiv);
}
});
});
entireHTML = $(tempDiv).html();
Since you need the HTML content of the 'option' elements, they're cloned and wrapped in a temporary div so that the inner HTML of that temporary div is copied and appended to our final HTML string.
Check it out for yourself : JSFiddle Test Link

Get the clickked row option dropdown menu value in Jquery

i have around 15 row in a table, each row comprises of a dropdown menu. Here is the code of my dropdown
<td headers="Vehicles">
<select id = "Dropdown">
<%if (ViewData.Model.Details.ElementAt(i).vehicle == "Car")%>
<%{%>
<option value="car" selected="selected">car</option>
<option value="Bus">Bus</option>
<option value="Lorry">Lorry</option>
<%} %>
<%else if (ViewData.Model.Details.ElementAt(i).vehicle == "Bus")%>
<%{%>
<option value="car" >car</option>
<option value="Bus" selected="selected">Bus</option>
<option value="Lorry">Lorry</option>
<%} %>
<%else if (ViewData.Model.Details.ElementAt(i).vehicle == "Lorry")%>
<%{%>
<option value="car">car</option>
<option value="Bus">Bus</option>
<option value="Lorry" selected="selected">Lorry</option>
<%} %>
</select>
</td>
Now if i click on 4th row, i need what is the option value selected in 4th row.
When i click on 3rd column of a row, i m reading 1st column text. Like this i need to read the option selected in the row.
$('#Requests td:nth-child(3)').bind('click', function () {
var id = $(this).parents('tr:first').find('td:eq(0)').text();
});
you can do like this:
$('#Requests td:nth-child(3)').bind('click', function () {
var id = $(this).parents('tr:first').find('td:eq(0)').text();
var selected = $(this).parents('tr:first').find('td:eq(0)').find('select#Dropdown').val();
});
you should be using on as it is recommended:
$('#Requests td:nth-child(3)').on('click', function () {
var id = $(this).parents('tr:first').find('td:eq(0)').text();
var selected = $(this).parents('tr:first').find('td:eq(0)').find('select#Dropdown').val();
});
Try this:
$('#Requests td').on('click', function () {
var id = '';
var ddVal = $(this).closest('tr').find('select :selected').val();
if($(this).index() === 2){
var id = $(this).closest('tr').find('td:eq(0)').text();
}
console.log(id);
console.log(ddVal);
});
And there in your code i assume you are not applying same ids for multiple select dropdown element. If this is the case then i would say that is not a valid HTML markup you have to give different ids to the select elements or you can change the id attribute to class.
First of all you cannot use same id for select tag in multiple places, so change it to class like
class="Dropdown"
You need to find selected value in dropdown like below code
$("#tableId tr").click(function() {
var selectedOption = $(this).find(".Dropdown").val();
alert(selectedOption );
});
This can be obtained by simply assigning a class to your dropdown menu
See the jsfiddle
http://jsfiddle.net/3bgQ9/1/
$(function(){
$(".sel").change(function(){
alert($(this).val());
});
});

How to get different selected values in javascript?

Hello everyone how can I get two values from different select boxes? I get first value in my select box but I can't get the second value from another select box.Here is my javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var select = document.forms[0].sel;
var select2=document.forms[0].sel2;
select.onchange = function () {
var value = select.options[select.selectedIndex].value; // to get Value
alert(value);
}
select2.onchange = function () {
var value2 = select2.options[select2.selectedIndex].value; // to get Value
alert(value2);
}
});
</script>
<form>
<SELECT NAME="sel" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
<form>
<SELECT NAME="sel2" onChange="split(selected value)">
<OPTION VALUE=1>Milk</option>
<OPTION VALUE=2>tea</option>
<OPTION VALUE=3>water</option>
<OPTION VALUE=4>coffee</option>
</SELECT>
</form>
The second select box is in the second form. So:
var select2 = document.forms[1].sel2;
That said, you can actually use jQuery for these things:
// bind a change event handler to the second select
$("select").eq(1).on("change", function() {
alert( $(this).val() );
});
jQuery Tip - Getting Select List Values
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
$(document).ready(function () {
$('#sel').change(function(){ $('#sel option:selected').val(); });
give id to your select control
<SELECT id="sel">
with help of jQuery ( i suggest the logic, not the solution )
$(document).on('change', 'select', function(){
var selecetdOption = $(this).val();
alert(selecetdOption );
});​
Working Demo
You have wrong into your javascript because you have put
var select2=document.forms[0].sel2;
try to put
var select2=document.forms[1].sel2;
and it works!

Categories

Resources