jquery inArray not found value - javascript

I'm trying to find selected value in array but what i tried so far not working:
var array = [0, 74];
$('select').change(function() {
var selected = $('select option:selected').val();
if ($.inArray(selected, array) != -1) {
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>
it works with $.each but i don't want use any loop my goal is get this with inArray. if selected value is 0 or 74 it should alert found but it not works.

Use indexOf() function for find in array.
Chanhe type selected to integer parseInt() (array is integers)
var array = [0, 74];
$('select').change(function() {
var selected = parseInt($('select option:selected').val(), 10);
if(array.indexOf(selected)!=-1){
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>

val returns a string and inArray does strict comparison
var array = [0, 74];
$('select').change(function() {
var selected = $('select option:selected').val();
// convert to a number
if ($.inArray(+selected, array) != -1) {
alert('found');
} else {
alert('not found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="0" selected="selected">----</option>
<option value="59">ss</option>
<option value="61">aa</option>
<option value="62">zz</option>
<option value="60">yy</option>
<option value="74">xx</option>
</select>

Related

How can I search optgroup label with jQuery

I have a list with the states of the United States in a select and I need filter by the optgroup label.
For example:
If I search for Alabama, I need to return to another select with Birmingham and Huntsville
I'm using this jQuery code and this code works when I search by options, but I need search by groups.
How can I change the jQuery to return only the cities of the states in which I search?
Here is my working code: https://jsfiddle.net/km7s9er5/
Thanks in advance for someone helping me with this
$(document).ready(function() {
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;
var options = [];
$('#myfiltercities_id').hide();
$(select).find('option').each(function() {
options.push({
value: $(this).val(),
text: $(this).text()
});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
$('#myfiltercities_id').hide();
var options = $(select).empty().data('options');
var search = $(this).val().trim();
var regex = new RegExp(search, "gi");
$.each(options, function(i) {
var option = options[i];
if (option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
if (selectSingleMatch === true && $(select).children().length === 1) {
$(select).children().get(0).selected = true;
}
});
});
};
$(function() {
$('#myfiltercities_id').filterByText($('#textbox'), true);
$("select option").click(function() {
alert(1);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select name="myfiltercities" id="myfiltercities_id">
<option value=""></option>
<optgroup label="AL"></optgroup>
<optgroup label="Alabama">
<option value="123">Birmingham</option>
<option value="123">Huntsville</option>
</optgroup>
<optgroup label="AK"></optgroup>
<optgroup label="Alaska">
<option value="456">Anchorage</option>
<option value="789">Juneau</option>
<option value="135">Fairbanks</option>
</optgroup>
<optgroup label="AZ"></optgroup>
<optgroup label="Arizona">
<option value="198">Phoenix</option>
<option value="065">Tucson</option>
</optgroup>
<optgroup label="AR"></optgroup>
<optgroup label="Arkansas">
<option value="835">Little Rock</option>
</optgroup>
<optgroup label="CA"></optgroup>
<optgroup label="California">
<option value="402">Los Angeles</option>
</optgroup>
</select>
Consider the following code.
https://jsfiddle.net/Twisty/zvtymk1r/29/
HTML
<form action="/action_page.php">
<label for="fname">Find City</label>
<input type="text" id="textbox" name="textbox"><br><br>
<select name="myfiltercities" id="myfiltercities_id">
<option value=""></option>
<optgroup label="Alabama" data-abbr="AL">
<option value="123">Birmingham</option>
<option value="123">Huntsville</option>
</optgroup>
<optgroup label="Alaska" data-abbr="AK">
<option value="456">Anchorage</option>
<option value="789">Juneau</option>
<option value="135">Fairbanks</option>
</optgroup>
<optgroup label="Arizona" data-abbr="AZ">
<option value="198">Phoenix</option>
<option value="065">Tucson</option>
</optgroup>
<optgroup label="Arkansas" data-abbr="AR">
<option value="835">Little Rock</option>
</optgroup>
<optgroup label="California" data-abbr="CA">
<option value="402">Los Angeles</option>
</optgroup>
</select>
</form>
JavaScript
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;
$('#myfiltercities_id').hide().children().hide();
$(textbox).on("change keyup", function(e) {
$('#myfiltercities_id').hide().children().hide();
var search = $(this).val().trim().toLowerCase();
if (search.length >= 2) {
$('#myfiltercities_id').show();
$("optgroup", select).each(function(i, el) {
var label = $(el).attr("label").toLowerCase();
var abbr = $(el).data("abbr").toLowerCase();
if (search.length == 2) {
if (abbr == search) {
console.log(search, label, abbr);
$(el).show();
}
} else {
if (label.indexOf(search) >= 0) {
console.log(search, label, abbr);
$(el).show();
}
}
});
}
});
});
}
$(function() {
$('#myfiltercities_id').filterByText($('#textbox'), true);
$("select option").click(function() {
alert(this.value);
});
});
First your HTML Structure was not conducive to a proper search. The abbreviation had no correlation with the results. I moved this to a Data attribute associated with the cities.
Your search feature was originally designed for Option elements and not good for groups. Also it was re-adding Options back to the select. It seemed overly complex.
I find it easier, when filtering, to simply Hide all items and then Show items that match the filter. based on the number of characters in the input, we might be searching for an abbreviation or a full state name. This is an easy condition to look at.
So if the User searches for "al", they will get Alabama, but if they then continue to "ala", they will Alabama and Alaska.

Remove the duplicate values and combinations in html select option

I have a dynamically generated <select> field with <option>.
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
I would like to remove the duplicate occurrences and combinations. The final <select> field with <option> should look like :
<select>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
</select>
Here is how my fiddle looks like. Been trying to solve this for hours.
var values = [];
$("select").children().each(function() {
if (values.length > 0) {
var notExists = false;
for (var x = 0; x < values.length; x++) {
var _text = this.text.replace(/\s/g, "");
var value = values[x].replace(/\s/g, "");
if (values[x].length > _text.length) {
//console.log('>>+', value, ' || ', _text, value.indexOf(_text))
notExists = value.indexOf(_text) > -1 ? true : false;
} else {
//console.log('>>*', value, ' || ', _text, _text.indexOf(value))
notExists = _text.indexOf(value) > -1 ? true : false;
}
}
if (notExists) {
//this.remove();
values.push(this.text);
}
} else {
values.push(this.text);
}
});
Any help to solve this is appreciated.
You can use map() to return all options text and use split() on white-space. Then to remove duplicates you can use reduce() to return object. Then you can empty select and use Object.keys() to loop each property and append to select.
var opt = $("select option").map(function() {
return $(this).text().split(' ')
}).get();
opt = opt.reduce(function(o, e) {return o[e] = true, o}, {});
$('select').empty();
Object.keys(opt).forEach(function(key) {
$('select').append(' <option value="">'+key+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
You can loop through each of this children text , then use substring to get the first text & put it in an array.
Once done empty the select element and append the newly created options
var _textHolder=[]; // NA empty array to hold unique text
var _options="";
$("select").children().each(function(item,value) {
var _textVal = $(this).text().trim(); // Remove white space
//get the first text content
var _getText = _textVal.substr(0, _textVal.indexOf(" "));
// if this text is not present in array then push it
if(_textHolder.indexOf(_getText) ==-1){
_textHolder.push(_getText)
}
});
// Create new options with items from _textHolder
_textHolder.forEach(function(item){
_options+='<option value="">'+item+'</option>'
})
// Empty current select element and append new options
$('select').empty().append(_options);
JSFIDDLE
I would do with pure JS ES6 style. This is producing a words array from the whitespace separated options element's innerText value regardless the words are in the front, middle or the end; and it will create a unique options list from that. Basically we are concatenating these arrays and getting it unified by utilizing the new Set object. The code is as follows;
var opts = document.querySelector("select").children,
list = Array.prototype.reduce.call(opts, function(s,c){
text = c.innerText.trim().split(" ");
return new Set([...s].concat(text)) // adding multiple elements to a set
},new Set());
list = [...list]; // turn set to array
for (var i = opts.length-1; i >= 0; i--){ //reverse iteration not to effect indices when an element is deleted
i in list ? opts[i].innerText = list[i]
: opts[i].parentNode.removeChild(opts[i]);
}
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>

select option value jquery

i have a bit of problem to deal with the option value in jquery. which i have 2 kind of select and one of theme contain an array. some how i dont know how to compared them.
example:
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
script:
$(function(){
var $article = $('#article > option').each(function(){
//var $v = $(this).val();
//console.log($v);
return $(this).val();
});
$('#categorie').on('change', function(){
var $e = $(this).val();
console.log($e);
if($e == $article){
// here should be the value from the article was choosed from category
}else{
console.log('there are no entries')
}
});
})
but i dont know how to compare theme properly. and it should be if #category [1,2] selected then the #article 1 and 2 only shown in option and the other should be hidden. any kind of idea or suggestion thank you very much. best regard.
You can use something like that. It works for me.
Here is html.
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
And here is jquery.
$(document).ready(function(){
function checkData(value){
var $e = value;
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
}
$('#category').change(function(){
checkData($(this).val());
});
checkData($('#category').val());
});
I think that may help you.
Thanks
First of all there is a typo categorie. It should be category
Try this
var opts = [];
$('#article > option').each(function(){
opts.push($(this).val());
});
console.log(opts)
$('#category').on('change', function(){
var $e = $(this).val();
var present = false;
$(opts).each(function(i,v){
if($e[1]==v){
present= true;
console.log($e[1])
}
});
if(!present){
console.log('there are no entries')
}
});
Demo
You need to get the select value [1,2], then use JSON.parse to make that and array. Then you can search it.
var $article = [];
$(function() {
$article = $('#article > option').map(function() {
return parseInt(this.value);
}).get();
console.log($article);
$('#category').on('change', function() {
var $e = JSON.parse(this.value);
console.log($e);
valid = false;
$.each($e, function(i, val){
valid = valid || $.inArray(val, $article) != -1;
});
if (valid)
alert('Exists' + $e.join())
else
console.log('there are no entries')
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="category">
<option value="[1,2]">category fruit</option>
<option value="[3,4]">category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
try this:
if($e.indexOf($article)!=-1){
}else{
console.log('there are no entries')
}
Try this option, working example jsfiddle
$('#categorie').on('change', function(){
var $e = $(this).val();
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
});
The value inside first select element is not an array, it just a string, remove bracket and leave only number with comma separated like following :
HTML
<select id="category">
<option value="1,2"> category fruit</option>
<option value="3,4"> category vegies</option>
</select>
<select id="article">
<option value="">chose</option>
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
Js
(first option)
// use this
$('#category').change(function(){
var cat = $( this ).val().split(',');
$('#article option').hide()
$.each(cat,function(i,e){
$('#article option[value="'+e+'"]').show()
})
});
(second option)
//or use this : filter out only matched element
var cacheElem = $('#article option').detach();
$('#category').change(function(){
$('#article option').remove();
var cat = $( this ).val().split(',');
var h = cacheElem.filter(function(){
return $.inArray(this.value, cat) !== -1 && this
});
$('#article').append(h)
});
DEMO
I'm not sure of your flexibility to change the category option value attribute but I took the liberty to take another approach to your issue.
I created an object with a list of possible items to display.
The select id="category" options value is the name of the list of items I want to display.
When the category changes I update the article select with only the list of items I want to show.
<select id="category">
<option value="fruits"> category fruit</option>
<option value="vegies"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
</select>
as for the JavaScript
$(function(){
var items = {
fruits: ["banana", "mango"],
vegies: ["letus", "spinash"]
};
var current = items[0];
var updateOptions = function(cat_in) {
current = cat_in;
output = "";
for(var i = 0; i<items[cat_in].length; i++) {
output += '<option value="'+i+'">'+items[cat_in][i]+'</option>';
}
return output;
};
$('#category').on('change', function(){
var $e = $(this).val();
if($e == current) return;
var options = updateOptions($e);
$("#article").empty().append(options);
});
});
Here is a live example: https://jsfiddle.net/marioandrade/mkt16n1g/1/
Seems pretty simple:
$('#category').on('change', function() {
var currentCategory = $(this).val();
// reset and show/hide group items
$('#article').val("").find('option').each(function(index) {
$(this).toggle(!(currentCategory.indexOf($(this).val()) === -1));
});
}).triggerHandler('change');

Add comma to Selected Pop Up Fields

I selected multiple fields from select box 1 and select box 2. Then hit the execute button, my alerts shows "AnimalBird,WolfFox".
I have googled how to make it add a comma when I select multiple fields when I hit the execute button, but no luck. I would like it to read "Animal,Bird,Wolf,Fox" with commas.
Below is my code
html:
<select name="select1" id="select1" size="4" multiple>
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2" size="4" multiple>
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM</option>
</select>
<input type="button" id="button" value="Execute" />
javascript:
$("#select1").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and
kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
console.log(id);
var options = $(this).data('options').filter(function () {
return $.inArray(this.value, id) > -1
});
$('#select2').html(options);
});
$('#button').click(function() {
var str = $('#select1 option:selected').text() +','+ $('#select2 option:selected').text();
alert(str);
});
If possible I would like the selected fields to show below the execute button.
Thank you everyone for your help.
Try this to loop through
http://jsfiddle.net/xd7pq22y/
$("#select1").change(function() {
if($(this).data('options') == undefined){
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options',$('#select2 option').clone());
}
var id = $(this).val();
console.log(id);
var options = $(this).data('options').filter(
function () {
return $.inArray(this.value, id) > -1
});
$('#select2').html(options);
});
$('#button').click(function() {
var values = [];
$('#select1 option:selected').each(function() {
values.push($(this).text());
});
$('#select2 option:selected').each(function() {
values.push($(this).text());
});
$("#wrapper").html(values.join(", "));
});
Just do this, with a tidy way:
$('#button').click(function() {
var values = [];
$('#select1 :selected, #select2 :selected').each(function() {
values.push($(this).text());
});
alert(values.join(','));
});
What we use here is the below techniques:
$().each() method: Loop on the selected element set;
Array.push() method: Append one string to an array once;
Array.join(separator) method: just join the strings in the array;

How can I remove options with the same text from a select element?

I have a select element that shows multiple options with the same text:
<select name="tur" id="tur">
<option value="1">a</option>
<option value="2">a</option>
<option value="3">a</option>
<option value="4">a</option>
<option value="5">b</option>
<option value="6">b</option>
<option value="7">c</option>
<option value="8">d</option>
</select>
Using JavaScript, I would like to remove these duplicates so that only one of each is shown:
<select name="tur" id="tur">
<option value="1">a</option>
<option value="5">b</option>
<option value="7">c</option>
<option value="8">d</option>
You can loop through the <option> elements, checking each one to see if its text content is in an array. If it is, remove the <option>. If not, add its content to the array. This will remove options that are redundant in the list.
Try it out: http://jsfiddle.net/FXq8W/
​var array = [];
​$('#tur option').each(function() {
var $th = $(this);
var text = $th.text();
if( $.inArray(text, array) > -1 ) {
$th.remove();
} else {
array.push( text );
}
});​​​​​​​​​​​​​​
http://api.jquery.com/jquery.inarray/
var remove = [], values = {}, value, i;
var options = document.getElementById('tur').getElementsByTagName('option');
for (i=0; i<options.length; i++) {
value = options[i].innerHTML.replace(/^\s*|\s*$/g, '');
if (value in values) remove.push(options[i]);
else values[value] = true;
}
for (i=0; i<remove.length; i++) {
remove[i].parentNode.removeChild(remove[i]);
}

Categories