How can I get 2 different variables from select box and hidden inputs in jquery, i.e:
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text1">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text2">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text3">
so I have 3 select boxes with 3 hidden inputs, how can I get the value of each select boxed and the text that is attached to? i.e: if I select like this:
Select item is 1 and text is Text1
Select item is 3 and text is Text2
Select item is 2 and text is Text3
Thanks in advance
function getValues() {
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
});
}
If you want to list the values on change:
$('select.startID,input[type="hidden"]').change(getValues);
Demo (modified a bit):
http://jsfiddle.net/6ev9evew/
NOTE
The updates below are not answers for the original question, but the question's author keeps posting extra questions in the comments! So the solution is above!
UPDATE:
As I can understand this is what you looking for:
function getValues() {
var me = this;
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
if (el === me) return false;
});
}
So basically we stop the loop at the actual element. But it works only if you pass this function to an event handler.
DEMO 2: http://jsfiddle.net/6ev9evew/1/
UPDATE 2:
So, according to the third question, this is a version of the implementation. As I mentioned below in the comments section, there are multiple ways to implement it. This implementation uses that the array indexes are always in order.
function getValues() {
var result = [];
var me = this;
$('select').each(function (idx, el) {
var $el = $(el);
result[10*$el.val()+idx]=("Select item is " + $el.val() + " and text is " + $el.next('input[type="hidden"]').val()+'<br />');
if (me === el) return false;
});
$('#res').html(result.join(''));
}
$('select.startID,input[type="hidden"]').change(getValues);
DEMO 3:
http://jsfiddle.net/6ev9evew/2/
But you can also implement it with array.sort(fn) but than you do a second iteration on the result set.
Anyway if you have more than ten selects in your real code, don't forget to modify the multiplier at result[10*$el.val()+idx] !
If you want to know the value of the changed select (when the user selects a value on any of them) and also get the value of the input type hidden which is next to it, that's the way:
$('.startID').on('change', function () {
var sel = $(this).val();
var hid = $(this).next('input[type=hidden]').val();
console.log('Select item is ' + sel.toString() + ' and text is ' + hid.toString());
});
Demo
UPDATE
To achieve what you've asked in the comments, you can do it like this:
// Create two arrays to store the values.
var sel = [];
var hid = [];
$('.startID').on('change', function () {
// Put the selected values into the arrays.
sel.push($(this).val());
hid.push($(this).next('input[type=hidden]').val());
console.log(sel);
console.log(hid);
for (var i = 0; i < sel.length; i++) {
console.log('Select item is ' + sel[i].toString() + ' and text is ' + hid[i].toString());
}
});
Demo
Related
I have a select with options and when a user selects an option, it is removed from the select and displayed as a button. When the button is pressed, the option goes back to my select. Everything works fine with mouse click, but if we navigate with the arrows key, the user can select my first option which is "choose fruit". How do I make it unselectable? disabled="disabled" doesn't work. Here's a jsfiddle http://jsfiddle.net/gbjcw1wp/2/. To reproduce the problem, select a fruit, then press Up arrow key on your keyboard.
EDIT : ONLY HAPPENS IN GOOGLE CHROME.
Disabling arrow keys work, but i'd like another way of accomplishing this.
HTML:
<select id="combobox" onchange="cbchange();">
<option selected="selected">Choose Fruit</option>
<option value="apple">apple</option>
<option value="pear">pear</option>
<option value="orange">orange</option>
<option value="banana">banana</option>
</select>
<br>
<br>
<div id="buttons"></div>
Javascript :
var fieldnames = [];
var valuenames = [];
function sortComboBox() {
document.getElementById("combobox").remove(0);
var my_options = $("#combobox option");
my_options.sort(function (a, b) {
if (a.text.toUpperCase() > b.text.toUpperCase()) return 1;
if (a.text.toUpperCase() < b.text.toUpperCase()) return -1;
return 0;
});
$("#combobox").empty().append('<option>Choose Fruit</option>').append(my_options);
$('#combobox option:first-child').attr("selected", "selected");
}
function cbchange() {
var index = $('#combobox').get(0).selectedIndex;
var text = $('#combobox option:selected').text();
var selectedItem = $('#combobox').val();
$('#buttons').append('<table class="ui"><tr><td class="variable">' + text + '</td><td class="icon"><span id="' + selectedItem + '" class="icon ui" value="X" onclick="addOption(\'' + text + '\',this.id)">X</span></td></tr></table>');
$('#combobox option:eq(' + index + ')').remove();
fieldnames.push(text);
valuenames.push(selectedItem);
}
function addOption(text, selectedItem) {
for (var i = valuenames.length - 1; i >= 0; i--) {
if (valuenames[i] === selectedItem) {
valuenames.splice(i, 1);
fieldnames.splice(i, 1);
}
}
$("#combobox").append($("<option></option>").val(selectedItem).text(text));
$('#' + selectedItem).parent().parent().parent().parent().remove();
sortComboBox();
}
A simple change to your code can resolve your problem.
Give the default option some weird value. Eg:
<option value="null" selected="selected">Choose Fruit</option>
And append the follow code the the start of your cbchange() function.
if($('#combobox').val()=="null"){
return false;
}
See jsfiddle example
having a bit of trouble here, any help would be greatly appreciated...
I am trying to hide and show a bunch of list items based on several classes assigned to them.
In my JS Fiddle Example I have several items with classes relating to their description.
I have managed to hide and show these, but complex selections are not possible...
example: If I wanted to only see fabrics that are "premium", "blue" and "linen".
Something like this (that works lol) is what I am after...
$('.sel_range').click(function() {
range = document.getElementById("range").value;
if ($('.fabric_option').hasClass(range)) {
$('.' + range).fadeIn('fast', function() {
!$('.fabric_option').hasClass(range).fadeOut("fast");
});
}
});
Something like this should work
var selects = $('#range, #fabric, #colour');
selects.on('change', function() {
var el = selects.map(function(i, item) {
return item.value.indexOf('all_') === 0 ? '' : '.' + item.value;
}).get().filter(function(x) {
return x.length;
}).join('');
$('#fabric_options li').show().not(s?s:'*').hide();
});
FIDDLE
It starts with showing all the list items, then joins the values together to create a clas selector, leaving out the class if all_something is selected etc. and then hides everything that doesn't match, and if nothing is selected excludes everything.
I think it can be solved like this:
var range, fabric, colour;
var updateShown = function() {
$('li').show()
if (range) {
$('li:not(.' + range + ')').hide();
}
if (fabric) {
$('li:not(.' + fabric + ')').hide();
}
if (colour) {
$('li:not(.' + colour + ')').hide();
}
}
// Range
$('#range').change(function() {
range = $(this).val();
updateShown();
});
// Fabric
$('#fabric').change(function() {
fabric = $(this).val();
updateShown();
});
// Colour
$('#colour').change(function() {
colour = $(this).val();
updateShown();
});
With value="" of each select first option
<select id="range">
<option class="sel_range" value="">All Ranges</option>
<option class="sel_range" value="luxury">Luxury</option>
<option class="sel_range" value="premium">Premium</option>
<option class="sel_range" value="base">Base</option>
</select>
<select id="fabric">
<option class="sel_fabric" value="">All Fabrics</option>
<option class="sel_fabric" value="leather">Leather</option>
<option class="sel_fabric" value="linen">Linen</option>
<option class="sel_fabric" value="cotton">Cotton</option>
</select>
<select id="colour">
<option class="sel_colour" value="">All Colours</option>
<option class="sel_colour" value="red">Red</option>
<option class="sel_colour" value="blue">Blue</option>
<option class="sel_colour" value="green">Green</option>
</select>
jsFiddle demo
what about this?
$('#range').on('change',function () {
range = $("#range").val();
$('li').each(function(){
if(!$(this).hasClass(range)){
$(this).hide();
}else{
$(this).show();
}
});
});
// just for range, rest in fiddle
http://jsfiddle.net/J3EZX/6/
If you're using jQuery, just string them together with a . and no space, e.g.:
$(".linen.red.base").text("Help! I'm being replaced!");
How can I find the index of a dropdown for a given value using jQuery?
Here is my dropdown with three values:
admin
mananger
employee
I'm able to get the index of the selected value like below
var index = $("#mydropdown").find("option:selected").val();
But I need to know the index of manager by passing manager as an argument to a jQuery function to get the index
I tried like this but it's not working
var index = $("#mydropdown").find("manager").val();
I think you need something like this:
js
$("select option[value='manager']").index()
html
<select>
<option value="admin">admin</option>
<option value="manager">mananger</option>
<option value="employee">employee</option>
</select>
fiddle
You can either use :contains or .filter(). I personally prefer .filter():
var index = $("#mydropdown").find(":contains(manager)").val();
//Or
var index = $("#mydropdown").filter(function(){
return $.trim($(this).text()) === "manager";
}).val();
This assume your drop down look like this :
<select>
<option value="1">admin</option>
<option value="2">manager</option>
<option value="3">employee</option>
</select>
Note: If you need to force the user to make a selection use an empty option and then have code check for a value ='0' or an index of zero respectively. I have added an empty option in both implementations below for this purpose.
Implementation #1:
function optionchanged()
{
var i = $("#option1").val();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
}
Assign index to value property in each option allows you greater control over the value returned.
<select id="option1" onchange="optionchanged();">
<option value="0"></option>
<option value="1">Admin</option>
<option value="2">Manager</option>
<option value="3">Employee</option>
</select>
The Console Output looks like this:
Selecting 'Admin' produces:
The Index of option selected is: 1
The Text of option selected is: Admin
Selecting 'Employee' produces:
The Index of option selected is: 3
The Text of option selected is: Employee
Implementation #2:
If you don't want to add the index to value you can reference the index directly in jQuery like this:
function optionchanged()
{
//var i = $("#option1 ").val();
var i = $("#option1 option:selected").index();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
//alert("Value of option 1 is: " + index);
}
<select id="option1" onchange="optionchanged();">
<option></option>
<option>Admin</option>
<option>Manager</option>
<option>Employee</option>
</select>
The console output will look the same as above.
I am using jquery to duplicate several html fields based on user's selection. However, I met an interesting problem. In general, I am asking users to select how many applications they want:
if there is only one application:
a. One need to choose application method (for simplicity, only 'aerial' is available); b. after selecting 'aerial', it will ask you for the further information, chemically application method (CAM).
if they choose two applications, jquery code will clone and rename the necessary questions for you.
My problem is when I choose there are two applications, the sub-question 'CAM' will not show up. After some trouble shoot, I found the problem could be in this javascript :$('.app_method:last').find('select').change(function(). The statement, automatically increase my loop index by one (Can anyone tell me why this will happen?), which mismatch the code.
Here is a DEMO for my code:
Below is my html code:
<div class="articles">
<table align="center">
<tr><th><label for="id_NOA">Number of applications:</label></th><td><select name="NOA" id="id_NOA">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></td></tr>
<tr><th><label for="id_Ap_m">Application method 1</label></th><td><select name="Ap_m" id="id_Ap_m">
<option value="" selected="selected">Select an application method</option>
<option value="1">Aerial</option>
</select></td></tr>
<tr><th><label for="id_CAM_1">Chemical application Method (CAM) 1</label></th><td><select name="CAM_1" id="id_CAM_1">
<option value="2">2-Interception based on crop canopy</option>
<option value="9">9-Linear foliar based on crop canop</option>
</select></td></tr>
</table>
</div>
jquery code:
$(document).ready(function() {
//this part of code controls inputs when there is only one application
$('#id_CAM_1').attr('id', 'id_1').closest('tr').addClass('method_options').hide();
$('#id_Ap_m').change(function() {
$('tr.method_options').hide();
if ($(this).val() == "1") {
$('#id_' + $(this).val()).closest('tr').show();
}
});
i = 1;
$('.articles').find('table').addClass('table');
$('#id_Ap_m').closest('tr').addClass('app_method');
$('#id_NOA').change(function() {
var total = $(this).val();
//remove all
$('.app_method').each(function(index) {
if (index != 0) $(this).remove()
});
//create new ones
for (var i = 2; i <= total; i++) {
alert('a=' + i);
$('.app_method:first').clone().appendTo('.table').find('label').text('Application method ' + i);
$('.app_method:last').find('select').attr('name', 'Ap_m' + i).attr('id', 'id_Ap_m' + i);
alert('b=' + i);
$('<tr class="method_options_1' + i + '" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM)' + i + '</label></th><td><select name="CAM_1_' + i + '" id="id_1_' + i + '"><option value="2">2-Interception based on crop canopy</option><option value="9">9-Linear foliar based on crop canop</option></select></td></tr>').appendTo('.table');
alert('c=' + i);
//The following statement increase the loop index by one, which causes me problems. Can
//anyone let me know why this could happen?
$('.app_method:last').find('select').change(function() {
alert('d=' + i)
$('.method_options_1').hide();
alert('e=' + i);
if ($(this).val() == "1") {
alert('e=' + i);
$('.method_options_1' + i).show();
}
})
}
})
})
I think this can be done much more simply: (fiddle: http://jsfiddle.net/QaHWz/)
<!DOCTYPE html><html><head></head><body>
<table align="center"><tbody>
<tr><th></th><td>Add Application</td></tr>
</tbody></table>
<table id="template" style="display:none"><tbody>
<tr>
<th><label for="id_Ap_m_{n}">Application method {n}</label></th>
<td>
<select class="Ap_m" name="Ap_m_{n}" id="id_Ap_m_{n}" data-application="{n}">
<option value="" selected="selected">Select an application method</option>
<option value="1">Aerial</option>
</select>
</td></tr>
<tr style="display:none" class="app_{n} method_1"><th><label for="id_CAM_{n}">Chemical Application Method (CAM) {n}</label></th><td><select name="CAM_{n}" id="id_CAM_{n}">
<option value="2">2-Interception based on crop canopy</option>
<option value="9">9-Linear foliar based on crop canopy</option>
</select></td></tr>
</tbody></table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
jQuery(function($) {
var applications = 0;
$('#add_application').click(function() {
applications++;
var last_row = $(this).closest('tr');
last_row.before(jQuery('#template tbody').html().replace(/{n}/g, applications));
});
$(document).delegate('.Ap_m', 'change', function() {
var app = $(this).data('application');
$('.app_'+app).hide();
$('.app_'+app+'.method_'+this.value).show();
});
});
</script>
</body></html>
EDIT: The problem you are having with .change() is that you are using the i variable , which gets incremented before the function is run. You need to get the value of i into the function another way. Here is one possible way you can do it:
$('.app_method:last').find('select').bind('change', { row: i }, function(event) {
var i = event.data.row;
alert('d=' + i)
// ...
});
The { row: i } bit causes jQuery to attach this data to the event object which is passed to the function. Then I create var i inside the scope of the function, which will not be affected by the i outside, and assign this value to it.
Say I have this dropdown:
<select name="color" multiple="multiple">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
So basically more than 1 color can be selected. What I'd like is that if a user selects red, and then clicks green, i'd like a function to be called each time which pops up a message box saying the color which was most recently clicked.
I've tried this:
<option value="red" onclick="alert('red');">Red</option>
<option value="green" onclick="alert('green');">Green</option>
<option value="blue" onclick="alert('blue');">Blue</option>
This works in firefox and chrome, but not in IE.
Any ideas?
$("select[name='color']").change(function() {
// multipleValues will be an array
var multipleValues = $(this).val() || [];
// Alert the list of values
alert(multipleValues[multipleValues.length - 1]);
});
Here's another examples: http://api.jquery.com/val/
The following code should do what I think you're after. Each time an item is selected, it compares the current list of selections against the previous list, and works out which items have changed:
<html>
<head>
<script type="text/javascript">
function getselected(selectobject) {
var results = {};
for (var i=0; i<selectobject.options.length; i++) {
var option = selectobject.options[i];
var value = option.value;
results[value] = option.selected;
}
return results;
}
var currentselect = {};
function change () {
var selectobject = document.getElementById("colorchooser");
var newselect = getselected(selectobject);
for (var k in newselect) {
if (currentselect[k] != newselect[k]) {
if (newselect[k]) {
alert("Option " + k + " selected");
} else {
alert("Option " + k + " deselected");
}
}
}
currentselect = newselect;
}
</script>
</head>
<body>
<select id="colorchooser"
name="color"
multiple="multiple"
onchange='javascript:change();'
>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</body>
</html>
It should work just as well in Internet Explorer as Firefox et al.
Since you using jQuery,I suggest you to take a look at this superb plugins. This plugins will transform a multiple select dropdown into a checkbox list, so user can select multiple values with easy.
To get the values, I suggest you use fieldValue methods from jQuery form plugins. It's a robust way to get value from any type of form element. Beside, you can use this plugins to submit your form via AJAX easily.
This will alert only the last (most recent) selected value. Calling $(this).val() using the select's change handler will return an array of all your selected values:
$(document).ready(function() {
$("select[name=color] option").click(function() {
alert($(this).val());
});
});
I am not sure what you exactly want. This will always alert the last selected color:
$(function(){
var selected = Array();
$('select[name=color] option').click(function() {
if($(this).is(':selected')) {
selected.push($(this).val());
}
else {
for(var i = 0; i < selected.length;i++) {
if(selected[i] == $(this).val()) {
selected = selected.splice(i,1);
}
}
}
alert(selected[selected.length -1])
});
});
The array is used to maintain the history of selected colors.
For the last clicked color, it is simpler:
$(function(){
$('select[name=color] option').click(function() {
alert($(this).val());
});
});
This is so complicated to accomplish that I used a simpler option of listing the items with a checkbox next to them and a select/unselect all button. That works much better and is also supported by IE. Thanks to everyone for their answers.