Find duplicate values in pairs - select dropdown - javascript

I have pair of text boxes. I need to find duplicate pair values in my select dropdown.
JSFIDDLE example
txt12 txt12
txt2 txt1
txt3 txt3
txt4 txt5
txt12 txt12
In my example, txt12 select pair is duplicated. I could possibly find each duplicate values by considering each select dropdowns.
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value); break;
}
else
values.push(select.value);
}
How is it possible to find duplicate pair of select dropdown values

You can use something like
function chkVal() {
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value);
}
else
values.push(select.value);
}
}
You have to just remove the break in the if block as it is moving out of the for loop in the first loop when it find text12.
Refer to the fiddle : "http://jsfiddle.net/sL6ofchd/9/"

With jQuery, try something like this:
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length );
});
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length + ' duplicates' );
duplicates.each(function(i) {
console.log( i, this, $(this).prev()[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<select>
<option value="txt2">txt2</option>
</select> <select>
<option value="txt1">txt1</option>
</select><br><br>
<select>
<option value="txt3">txt3</option>
</select> <select>
<option value="txt3">txt3</option>
</select><br><br>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<input type="button" value="save" class="check-value">

Related

Set <select> element depending on another <select> element

I need a select element's options to change depending on the value of another.
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.
Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.
JSFiddle
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.
Ex jquery code:
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/home/getstates";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Error retrieving states!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
Kindly refer this good article for the complete code:
http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx
Hope it will helps
Thanks
Karthik
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:
$(document).on('change', '#two', function() {
var option_to_add = $(this).find("option:selected").text();
var number_of_options = $('#two option').length
$('#one').append($('<option>', {
value: number_of_options,
text: option_to_add
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="cash">Cash</option>
<option value="money">Money</option>
</select>
<select id="two">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
<option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>
Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:
// dummy data array of arrays
var list = [
[11, "Eleven"],
[12, "Twelve"],
[13, "Thirteen"]
];
// click the button, replace the select contents
$('#btn').on('click', function() {
// build an array of option objects from an array of arrays
// see below
var opt_array = build_opt_array(list);
$('#sel').empty();
// add the new options
$(opt_array).each(function(index) {
$('#sel').append(opt_array[index]);
});
});
// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
var opt_array = [];
$(items).each(function(index) {
var new_option = $('<option>', {
value: items[index][0],
text: items[index][1]
});
opt_array.push(new_option);
});
return opt_array;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn">
Click me
</button>
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.
$("#two").focus(function() {
document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});

Change selected option value in dropdown

My dropdown looks like,
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Currently the dropdown shows options like "1011 2015-12-18 2015-12-22 ABC", that is fine but when user selects an option, I need to show only "CustomerId" i.e, 1011 in this case.
Your help is really appreciated. Thanks
Added script for focusout
customSelect.focusout(function () {
customSelectOptions.each(function (options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
$(this).blur();
}
});
});
var states = [];
var customSelect = $('#ddlCustomer');
var customSelectOptions = customSelect.children().children();
// Get each state then push them to the array
// Initial state declaration
customSelectOptions.each(function() {
var state = $(this).text();
states.push({ state: state });
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// On focus, always retain the full state name
customSelect.on('focus', function() {
customSelectOptions.each(function(index) {
$(this).text(states[index].state);
});
// On change, append the value to the selected option
$(this).on('change', function() {
customSelectOptions.each(function(options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// Un-focus select on finish
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1034_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Try like this.You have use regex with text value of selected option.
var ddlCustomer = document.querySelector('#ddlCustomer');
ddlCustomer.addEventListener('change',function(){
text = $(this).find("option:selected").text();
var value = text.match(/[0-9]+/);
$(this).find("option:selected").text(value);
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
See fiddle here https://jsfiddle.net/88cozeaz/1/
document.getElementById('#ddlCustomer').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text =$(this).val();
// Reset texts for all other but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};

checking for a duplcate value entered inside dropdown box with same class through jquery

There are 5 dropdowns having same class 'className'. I have to make sure that the values entered in the dropdowns are not duplicate.
now, I can access the dropdowns in jquery by class like this
$('.className').each(function(){
//my Ques:: code to check if duplicate values are entered by the user
});
My ques is stated inside the comment as "my ques"
You can check if the selected value is the same on the others using val and filter.
Filter:
Reduce the set of matched elements to those that match the selector or
pass the function's test.
Code:
function inputsHaveDuplicateValues() {
var hasDuplicates = false;
$('.className').each(function () {
var inputsWithSameValue = $(this).val();
hasDuplicates = $('.className').not(this).filter(function () {
return $(this).val() === inputsWithSameValue;
}).length > 0;
if (hasDuplicates) return false
});
return hasDuplicates;
}
$('button').click(function () {
alert(inputsHaveDuplicateValues());
})
Demo: http://jsfiddle.net/IrvinDominin/u3czyjt4/
I suppose there are a number of ways to solve this. For example, you can store the values of each combo in an array, and in each iteration, check if it was already stored in the array previously.
var values = [];
$('.className').each(function(element, index){
if (values.indexOf($(this).val()) >= 0) {
//already exists
return false; //break the loop
}
values[index] = $(this).val();
});
You can use the hashtable to check for duplicate entries. Check this fiddle:
http://jsfiddle.net/v025hkjn/
var hashtable = {};
$(".className").each(function () {
if(hashtable[this.text]) {
$(this).remove();
} else {
hashtable[this.text] = this.value;
}
});
for html may be like below
<select>
<option class='className' value="volvo">Volvo</option>
<option class='className' value="saab">Saab</option>
<option class='className' value="mercedes">Mercedes</option>
<option class='className' value="audi">Audi</option>
<option class='className' value="volvo">Volvo</option>
<option class='className' value="volvo">Volvo</option>
<option class='className' value="volvo">Volvo</option>
</select>
var array = []; // push all the values in array
$('.className').each(function(){
// check if the value is in array
if( $.inArray($(this).val(),array) > 0)
console.log('duplicate found ', $(this).val());
else
array.push($(this).val()
// if not insert into array
});

Removing select items depending on selected items

I have two select elements with times 12:00 AM through 11:45 PM,
both selects have the same options inside including text and value. Is it possible for example say I select 1:00 PM on the first select to remove all the options before 1:00 PM on the second select? I know I can detect the change with jquery
$('#select1').change(function(){
// in here do something to remove previous selects
});
Any help would be appreciated it.
Here is another version of the same where we allow for the user to change his first selection and still filter the second select correctly
$(document).ready(function() {
var to_mins = function(x) {
var p = x.split(':').map(function(v) { return parseInt(v, 10); });
return (p[0] * 60) + p[1];
};
$('#second').data('options', $('#second').find('option').toArray());
$('#first').change(function() {
var val = to_mins(this.value);
console.log(val);
$('#second').empty();
$('#second').data('options').filter(function(v) {
return to_mins(v.value) > val;
}).map(function(v) {
$('#second').append(v.cloneNode(true));
});
});
});
Try
$('#select1').change(function(){
var $this = $(this);
var index = $('option:selected', $this).index();
$('#select2 option').show().filter(':lt(' + index + ')').hide();
})
Demo: Fiddle
try this
$('#select1').change(function(){
var value = $(this).val();
$("#selectId > option").each(function() {
if(value > this.value)
$("#selectId option[value=this.value]").remove();
});
});
But the values need to be in ascending order for select boxes
HTML:
<select id="select1">
<option value="1">11h00</option>
<option value="2">11h15</option>
<option value="3">11h30</option>
<option value="4">11h45</option>
<option value="5">12h00</option>
<option value="6">12h15</option>
<option value="7">12h30</option>
<option value="8">12h45</option>
<option value="9">13h00</option>
</select>
<select id="select2">
<option value="1">11h00</option>
<option value="2">11h15</option>
<option value="3">11h30</option>
<option value="4">11h45</option>
<option value="5">12h00</option>
<option value="6">12h15</option>
<option value="7">12h30</option>
<option value="8">12h45</option>
<option value="9">13h00</option>
</select>
JS:
$(document).ready( function(){
$('#select1').change(function(){
var val = $(this).find('option:selected').prop('value');
$('#select2').find('option').show().each(function(){
if( $(this).prop('value') <= val ){
$(this).hide();
}
else{
return false;
}
});
});
});

option is still visible in select after remove()

Hi all I have two select fields, on select field first if user select option value one or two then in select field of second all options are visible but if it select option two in first then option two want to remove from select id second. Following is my code:
<script type="text/javascript">
var index3,str;
</script>
<select id="first" onchange="chk();">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<select id="second">
<option value = "one">one</option>
<option value = "two">two</option>
<option value = "three">three</option>
</select>
<script type="text/javascript">
function chk()
{
index3 = document.getElementById("first");
str= index3.options[index3.selectedIndex].value;
alert("str:"+str);
if (str=="two")
{
$("#second option[value='two']").remove();
}
else
{
if ( $("#second option[value='two']").length == 0 )
{
$("#second").append('<option value="two">two</option>');
}
}
}
</script>
In fiddle it works fine here, But on mobile problem is: If I select option two from select id second, and then select option value two in first select id, then also option two is visible in second select id, if I click on second select id then only it removes. But in jsFiddle it works perfect. Any suggestion will be appreciated, Thanks in advance.
Here i have done complete bin for above issue. please go through demo link.
Demo http://codebins.com/bin/4ldqp7p
HTML
<select id="first">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
<select id="second">
<option value = "one">
one
</option>
<option value = "two">
two
</option>
<option value = "three">
three
</option>
</select>
jQuery
$(function() {
$("#first").change(function() {
var optVal = $(this).val().trim();
if (optVal == "two") {
$("#second").find("option[value=" + optVal + "]").remove();
} else {
if ($("#second").find("option[value=two]").length <= 0) {
$("<option value=\"two\">two</option>").insertAfter($("#second").find("option[value='one']"));
}
}
});
});
Demo http://codebins.com/bin/4ldqp7p
check this Edit
$('#first').change(function() {
$("#second option[value='" + $(this).val() + "']").remove();
});
Your code looks a bit odd overall. If your intention is to remove the item from 'second' if it is selected in 'first', try this update: http://jsfiddle.net/NWbXt/58/
$(function() {
var first = $('#first'),
second = $('#second'),
removed;
first.change(function() {
var selected = first.val();
second.append(removed); //.. add back old option
removed = second.find('option[value="' + first.val() + '"]').remove();
}).trigger('change');
});​

Categories

Resources