jsfiddle
HTML:
<select class="s1"></select>
<select class="s2"></select>
JS:
var test = [
["a","bsafd","cfsaf"],
["b","cvxb","cfsf"],
["c","hjymb","cfsaf"],
["d","vhthb","fsfc","fasfsa"],
["e","fsdb","fsfac"],
["f","zxczb","vcxc","fsafsd"],
["g","yjhdb","bvcbc"],
["h","vbnvb","yutkfc"],
["i","nbcvnb","ndnfgnmc"],
["j","ikgnb","ncnc"],
["k","fgncb","kjuc"]
];
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
for(var i=0;i<test.length;i++){
if(test[i].indexOf(value)){
for(var j=0;j<test[i].length;i++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
I can get the first value from array test and append to the first select area. But I stacked on the second step. I want to append values to the second select area according to the user selection.
Fon instance, user select "a". The next two values should be append to the second area from the sub array which lead with "a".
Could someone tell me what am I done wrong and how to finish it?
Try the below code [check the inline comments where you did mistake],
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option value='"+test[i][0]+"'>"+test[i][0]+"</option>");
// -----------------^ add value to all options
}
$(".s1").on("change", function(){
var value = $(this).val();
$(".s2").html('');// first make the second drop down blank
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
for(var j=0,l=test[i].length;j<l;j++){
//----------------^ j++ not i++
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
Live Demo
Alternatively, if you make your json as key-value pair to differentiate the data for different drop down then it would more simpler to use it like,
// json where keys are used fro first drop down and its values are used for second one
var test = {
"a":["bsafd","cfsaf"],
"b":["cvxb","cfsf"],
"c":["hjymb","cfsaf"],
"d":["vhthb","fsfc","fasfsa"],
"e":["fsdb","fsfac"],
"f":["zxczb","vcxc","fsafsd"],
"g":["yjhdb","bvcbc"],
"h":["vbnvb","yutkfc"],
"i":["nbcvnb","ndnfgnmc"],
"j":["ikgnb","ncnc"],
"k":["fgncb","kjuc"]
};
$(function(){
$.each(test,function(i,v){
// store all keys to first drop down
$(".s1").append("<option value='"+i+"'>"+i+"</option>");
});
$(".s1").on("change", function(){
var value = this.value;
$('.s2').html('');
if(value){
// get the value for the key which is selected
$(test[value]).each(function(key,data){
$(".s2").append("<option value='"+data+"'>"+data+"</option>");
});
}
});
});
Working Demo
$(".s1").on("change", function(){
var value = $(this).val();
var option = '';
for(var i=0;i<test.length;i++){
/* Checking for first index */
if(test[i][0] == value){
for(var j = 1;j<test[i].length;j++){
/* creating options */
option += '<option>'+test[i][j]+'</option>';
}
}
}
/* remove previous options and prepend new option by selection */
$(".s2").empty().prepend(option);
});
Please try this..
check this fiddle
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
(var j=1;j<test[i].length;j++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
It is not a multi-dimension array, so you need to loop through or filter() the original array to find the matching row and then add the elements of that array starting from 1 instead of 0 to ignore the "key" value:
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
// find the first array which starts with value
var arr = test.filter(function(v){
return v[0] == value;
})[0];
// store a reference to .s2 so you don;t need to find it every time
var s2 = $(".s2");
// remove previous options
s2.empty();
for(var i = 1; i < arr.length; i++){
s2.append("<option>"+arr[i]+"</option>");
}
});
});
Updated Fiddle
Related
Notice that my first two table Data (Apple and Orange) are set to read-only. And I do have function for dynamic adding of row.
see this FIDDLE FOR DEMO
If the user click the Save button, all input field that detect duplicate of data from database or last duplicate of data from row which dynamically added, border-color will change to red.
$("#save").off("click").on("click",function(){
var $rows = $('#myTable tbody tr:not(:hidden)');
$rows.each(function(){
var $id = $(this).find('td input[type=\'text\']');
alert($id.val());
//Im stuck here, for checking column data is duplicate.
});
});
Im looking forward on using Jquery filter , like this :
$( "li" ).filter( "DUPLICATE DATA()" ).css( "border-color", "red" );
I am assuming you want to target the "Name" column, although you could easily change this to target all columns.
Basically, you want to go through the input elements, keeping a reference to the values you've already reviewed:
$("#save").off("click").on("click",function(){
var existing = [];
var duplicates = $('#myTable td:nth-child(3) input').filter(function() {
var value = $(this).val();
if (existing.indexOf(value) >= 0) {
return $(this);
}
existing.push(value);
});
duplicates.closest('tr').css('background-color', 'red');
});
JSFiddle
Edit: To avoid marking a read-only line as a duplicate, the process is a little less straightforward
$("#save").off("click").on("click",function(){
// Clear status of all elements
$('#myTable tr').css('background-color', 'none');
// Get all values first (Apple, Orange, etc) as strings
var allValues = $('#myTable td:nth-child(3) input').map(function() {
return $(this).val();
}).toArray();
// Iterate unique values individually, to avoid marking a read-only input as duplicate
var processedValues = [];
for (var i = 0; i < allValues.length; i++) {
var value = allValues[i];
if (value != '' && processedValues.indexOf(value) >= 0) continue;
var inputs = $('#myTable td:nth-child(3) input').filter(function() { return $(this).val() == value; });
// Check if this value is in one of the readonly
var readOnlyInput = inputs.filter(function() { return $(this).is('[readonly]'); });
if (readOnlyInput.length) {
inputs.not(readOnlyInput).closest('tr').css('background-color', 'red');
} else {
inputs.not(':first').closest('tr').css('background-color', 'red');
}
processedValues.push(value);
}
});
Updated JSFiddle
Could someone please help me handle this issue in jQuery
I have a requirement where I have two dropdowns:
The no of floors of the flat (numberOfFloors)
The flat where the user stays (whichFloorYouStay)
I need to remove all the invalid options from the second dropdown. How do I achieve this?
For example:
If a user select the numberOfFloors option as 3, then I should remove options 4 and 5 from whichFloorYouStay dropdown and just load 1,2,3 as whichFloorYouStay options.
Similarly, if a user select the numberOfFloors option as 1, then I should remove options 2,3,4,5 from whichFloorYouStay dropdown and just load 1 as whichFloorYouStay option.
Please find my JSBin link:
http://jsbin.com/sibufive/1/edit?html,js,output
Try this:
$(document).ready(function () {
//NEW CODE:
var floorsvals = new Array();
var lastvalue = Number.MAX_VALUE; //Useful for checking whether we need to append or remove elements - Initialize this with an arbitrarily large number
//Fill possible floor vals with value of <option>'s
$("#numberOfFloors option").each(function () {
floorsvals.push($(this).val());
});
//NOTE: If you already know the values of the numberOfFloors array, you can just add those values straight into the "floorsvals" array
//The above loop is just handy if you are dynamically generating a <select> list and don't already know the values
$("#numberOfFloors").change(function () {
alert($("#numberOfFloors").val());
var value = $("#numberOfFloors").val();
//NEW CODE:
//If we need to append...
if (value > lastvalue) { //This value is larger than the last value we just had
for (i = 0; i < floorsvals.length; i++) {
if (floorsvals[i] <= value && $('#whichFloorYouStay option[value=' + floorsvals[i] + ']').length === 0) { //Floor value is less than the selected maxvalue and an option with this floor value doesn't already exist...
$('<option value="' + floorsvals[i] + '">' + floorsvals[i] + '</option>').appendTo("#whichFloorYouStay"); //...So add that floor value
}
}
} else { //Otherwise, we need to remove
//OLD CODE:
$('#whichFloorYouStay option').each(function () { //Go through each option
if ($(this).val() > value) { //If this option's value is greater than the numberOfFloors value, remove it
$(this).remove();
}
});
}
//NEW CODE:
lastvalue = value; //Update last value chosen with this value
});
});
Here's a demo: http://jsbin.com/sibufive/40/edit
var value = $("#numberOfFloors").val();
should become
var value = $("#numberOfFloors").val();
value-=1
I would also suggest adding a value 0 to the first set of options one so you never have a user begin at 1 and try to move to the second menu
I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect.
i write this code,but it does work.
$("select.multiselect").on("change", function(e) {
if(e.added){
for(var i=0;i<this.options.length;i++){
var vals = $(this).select2("val");
for(var j=0;j<vals.length;j++){
if(this.options[i].value===vals[j]){
this.options[i].selected=true;
}
}
};
}
if(e.removed){
for(var i=0;i<this.options.length;i++){
if(this.options[i].value===e.removed.id){
this.options[i].selected=false;
}
};
}
});
how to do it?
It was more complicated then I thought but here is what I came up with:
$('select.multiselect').on('change', function(e) {
// the selected values
var vals = $(this).select2("val");
// selects contains all the OTHER select forms
var selects = $('select').not('#'+$(this).attr('id'));
// loop trough all the selects
for (var i = 0; i < selects.length; i++) {
//re-enable all options before
$(selects[i]).find('option').removeAttr('disabled');
// loop trough all the values
for (var j = 0; j < vals.length; j++) {
// disabled attribute
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
});
Here's a fiddle if you want to see the result in action
Make sure all your select elements have a unique id.
I found this online:
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var the_default = $(this).val();
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
As you can see, it grabs the text within a value attribute and sets it as the default_value. It then checks the current_value against the default.
I'm running into a problem.
In this example, we have an element like:
<input type="text" class="placeholder" value="potato">
If the user focuses and unfocuses the input, it works great - removing and repopulating with "potato".
However, let's say a user enters "ioqiweoiqwe", and then unfocuses the input (fills out the rest of the form"). They then go back to our input and delete all of their text, and click on another field. The input would be re-populated with "ioqiweoiqwe" - when really, we want it to be re-populated with the default_value. How do I manage to do this?
Yours sincerely,
a jQuery nub.
Note: I set up a jsfiddle here... a bit after some comments: http://jsfiddle.net/xmhCz/
I don't really know what the problem with that code is, but it looks like it was written by someone who didn't know much JavaScript. I rewrote the functionality:
$("input.placeholder").each(function() {
var me=$(this);
var defaultValue=me.val();
me.focus(function() {
if(me.val()===defaultValue) {
me.val("");
}
});
me.blur(function() {
if(me.val()==="") {
me.val(defaultValue);
}
});
});
Test it out on JSFiddle.
HTML inputs have defaultValue
I would like to know what the best way would be to loop through a dropdown list in html to see if and item has been selected or not.
I know in C# it would be something along the lines of
int selected = cmbFamily.SelectedIndex;
for (int loop = 0; loop < cmbFamily.Items.Count; loop++)
{
if (selected == -1)
{
MessageBox.Show("please select an item", "Please", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
how would I go about in doing this with javascript?
<tr style="font-size:12pt; font-weight:bold; color:#FFFFFF; font-family:High Tower Text;">
<td>Family to join:</td>
<td><select name="drpFamily">
<option/>-select-
<option/>Gambino
<option/>Genovese
<option/>Lucchese
<option/>Colombo
<option/>Bonanno
</select><font color="red">*</font></td>
</tr>
Kind regards
Arian
First off you HTML code is totally wrong. It is not </option>text, it is <option>text</option>
To loop through the options it is as simple as
//var options = document.getElementById("selectId").options;
var options = document.formName.selectName.options;
for(var i=0;i<options.length;i++){
if(options[i].selected){
alert(options[i].value);
}
}
but there is no need to loop through a single select. The easiest way is just to use selected index for a single select.
//var sel = document.getElementById("selectId");
var sel = document.formName.selectName;
var opt = sel.options[sel.selectedIndex];
alert(opt.value);
First: your HTML is wrong.
It should be
<option>-select-
...
or
<option>-select-</option>
...
If you just want the selected value, you can get it via the value attribute of the select element:
var value = document.getElementsByName('drpFamily')[0].value
This only works if there is only one element with name drpFamily. If not, you have to find an appropriate way to select it.
You might want to compare it against the first value (which is selected by default)
if(value !== '-select-')
You could also add a change event listener to the select element:
document.getElementsByName('drpFamily')[0].onchange = function() {
if(this.value !== '-select-') {
//a value other '-select-' than was selected
}
}