jQuery - get value from a select when there are several - javascript

I am dynamically inserting many selects on to my page depending on user inputs. The select lists are identical and share similar names.
When the user chooses an option, I want to grab that value. (In the end what I'm trying to accomplish is to disable the chosen value from all other lists, but re-enable it if the value is changed. But one step at a time)
I am assuming that I will need to use $(this) but I apparently do not know how to get the values from the second, third lists, and so on.
The HTML would be something like this:
<select name="category[first]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="category[second]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
** Many more lists with the same naming convention
As for my jQuery, I was trying something like this:
$('body').on('change', $('select[name^="category"]', function(){
alert( $(this).find('option:selected').val() );
});
But that only gives me the value from the first select, and not from any subsequent ones. My understanding is that I have to use $('body') or $('document') since they are dynamically created elements.
Any help would be appreciated, thank you.

Remove the $( before the selector. The selector needs to be a string, not jQuery object
$('body').on('change', 'select[name^="category"]', function(){
console.log( $(this).find('option:selected').val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select name="category[first]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="category[second]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

This is how I would do it: DEMO FIDDLE
$('body').on('change', 'select', function () {
var selected_value = $(this).val();
$('select option').each(function(){
if(this.value == selected_value){
$(this).prop('disabled', true);
} else {
$(this).prop('disabled', false);
}
});
});

Related

Storing multiple select option values in localStorage using select id as key

Context
First off, I am not a developer but I have tried to explain the desired outcome...
I want to use Vanilla JS for this solution.
The problem
I have multiple select dropdowns on the page and ideally want to be able to store the value onchange of each of the dropdowns.
<select name="Value1A" id="Value1A" onchange="storeValue()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="Value1B" id="Value1B" onchange="storeValue()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Essentially I want to achieve this...
This is of course not actual working code but hopefully explains what I am trying to do
function storeValue(){
localStorage.setItem(select.id, select.value);
}
i.e. I want to use the select id as the localStorage key - and onchange store the value of the option of that select field (onchange).
Any help would be really appreciated. Any questions or need to me to explain better, let me know.
Pass event inside your onclick handler
it will look like this
<select name="Value1A" id="Value1A" onchange="storeValue(event)">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
After inside your storeValue function get the id from event.target like this
function storeValue(event){
localStorage.setItem(event.target.id, event.target.value);
}
In your case you want to store and later retrieve those values.
// Add id:s and values:
<select> // select has children -> the children are the options.
// the children have values and id:s.
<option id ="1" value="0" >0</option>
<option id ="2" value="1" >1</option>
<option id ="3" value="2" >2</option>
<option id ="4" value="3" >3</option>
<option id ="5" value="4" >4</option>
<option id ="6" value="5" >5</option>
</select>
we begin by targeting the select tag and using "onchange" everytime someone clicks on the select the function gets triggered.
The "this" is the current context i.e we will be able to find the currently clicked on child of select which is an option, using this.selectedIndex which is the index number of the currently clicked on option i.e index number will be 0 for the top option and 1 for the next etc etc.
We use the index number inside this.children i.e the children of the select and by now we know the children in this case are the option tags.
document.getElementsByTagName('select')[0].onchange = function() {
var index = this.selectedIndex;
// console.log(this) to see what "this" prints out.
// above line returns the index number of selected
// option
var inputText = this.children[index].value;
// do -> console.log(inputText); to see for your self.
// above we use the index number on the range of options.
// The index number helps us find the option that was clicked.
// Now we add .value to to retrieve the value.
var id = this.children[index].id;
// same as above to retrieve id
localStorage.setItem(id, inputText);
// above saves variables id and inputtext to localstorage.
}

How to remove or hide duplicate value from dropdownlist in jquery

I have a dropdownlist. where i load my all due client list from database. but one client have one more due amount. so it's loads on my dropdownlist and make duplicate client name's,now i want to remove duplicate clients name.
Here is my dropdownlist.
<label class="form-label">Client Name</label>
<select class="form-control" name="client_id" id="client_id">
<option value="">-Select Client-</option>
#foreach($clients as $client)
<option value="{{$client->id}}">{{$client->client_name}}</option>
#endforeach
</select>
Here, is my tried jquery part.
$(document).ready(function(){
var map={};
$('#client_id').each(function(){
if(map[this.value])
{
$(this).remove();
}
map[this.value]=true;
});
});
You're very close.
Just change:
$('#client_id').each(function(){
to:
$('#client_id option').each(function(){
That will iterate through all the options instead of the single #client_id.
Snippet:
var map = {};
$('#client_id option').each(function() {
if (map[this.value]) {
$(this).remove();
}
map[this.value] = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="client_id">
<option value="">-Select Client-</option>
<option value="1">1</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Using .siblings() (to target sibling option elements), and Attribute Equals Selector [attr='']
$(".select option").val(function(idx, val) {
$(this).siblings("[value='"+ val +"']").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select">
<option value="">All</option>
<option value="com">.com 1</option>
<option value="net">.net 1</option>
<option value="com">.com 2</option> <!-- will be removed since value is duplicate -->
<option value="net">.net 2</option> <!-- will be removed since value is duplicate -->
</select>
How it works:
while options are accessed one by one (by .val()) - lookup for .sibling() options that have the same "[value='"+ this.value +"']" and .remove() them.
Preventing duplicate values using PHP is neater than using JavaScript in my opinion.
Solution 1
Eliminating the duplicates as you selecting from database via Eloquent.
// using Model
$clients = Client::get()->groupBy('client_name')->all();
// using DB::class
$clients = DB::table('clients')->get()->groupBy('client_name')->all();
Solution 2
Using Eloquent collect() to eliminate duplicate client_name
// $clients should be an array
#foreach( collect( $clients )->groupBy('client_name')->all() as $client )
<option value="{{ $client->id }}">{{ $client->client_name }}</option>
#endforeach
Solution 3
Using jQuery method, just in case you still want to remove the duplicates using jQuery
$(document).ready(function(){
var map={};
$('#client_id option').each(function(){
var val=$(this).val();
if( map[val] )
{
$(this).remove();
return; // continue to next loop
}
// Registering val to map list
map[val]=1;
});

Select dropdown value by textarea with jQuery

I have textarea (x1_typdv) and I want this:
If I write "3" to textarea, select option with value "3" in dropdown (x1_typdv2). I have this code but it not work, how to do it? Thanks.
$('#x1_typdv').change(function() {
$('#x1_typdv2').val($('#x1_typdv').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="x1_typdv" value="" name="x1_typdv">
<select name="x1_typdv2" id="x1_typdv2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
EDIT: I tried it again, it works for me if I use just normaln textarea. But I want use it for textarea which is filled by javascript (its calculations form), and here its not work. How to get the same value which is in teaxtarea to dropdown? Thanks.
$x1_typdv = parseFloat($('#x1_field_skrinka option:selected').attr('data-typdv')),
$x1_fieldTypdv.val($x1_typdv);
$x1_fieldTypdv = $('#x1_typdv');
Hi please check below answer its working..
$('#x1_typdv').keyup(function(e) {
if($('#x1_typdv').val()!="" && $("#x1_typdv2 option[value='"+$('#x1_typdv').val()+"']").length > 0)
$('#x1_typdv2').val($('#x1_typdv').val());
else if($('#x1_typdv').val()!="" && e.which != 8)
alert("Value doesnot exists.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="x1_typdv" value="" name="x1_typdv">
<select name="x1_typdv2" id="x1_typdv2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
Try to use below code
using Javascript:
document.getElementById("x1_typdv2").value = document.document.getElementById("x1_typdv").value;
OR
using jQuery
$('#x1_typdv2 option[value=' + $('#x1_typdv').val() + ']').attr('selected','selected');
You have to add jquery in your page and try this code :
$('#x1_typdv').on('change', function() {
$('#x1_typdv2').val($('#x1_typdv').val());
});
I noticed some browsers don't catch the change until blur
$(document).ready(function(){
$('#x1_typdv').on("keyup", function() {
$('#x1_typdv2').val($('#x1_typdv').val());
});
});
EDIT: I'd also add more solidity
$(document).ready(function(){
$('#x1_typdv').on("keyup", function() {
var value = $('#x1_typdv').val();
value && $('#x1_typdv2').val(value);
});
});
working fiddle ==> https://jsfiddle.net/tonysamperi/aepc4sbj/

jQuery select option last doesn't work

I've got a button and list of options. The idea is that when user clicks the button the default option changes from disabled to max value. And oposite - if the input is not checked, the default is again disabled.
But the value returns undefined. If I change the first and thelast to numeric values, everything works fine. What's wrong?
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected> -- choose -- </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
jQuery(function(){
jQuery(".input").click(function(){
var thefirst = jQuery(this).next('#select option:first').val();
var thelast = jQuery(this).next('#select option:last').val();
if( jQuery(this).is(':checked') )
jQuery(this).next('#select').val(thelast);
else
jQuery(this).next('#select').val(thefirst);
});
});
.next() gets the next sibling, so you need to get the select and use .find() or .children() afterwards:
var thefirst = jQuery(this).next('#select').find('option:first').val();
var thelast = jQuery(this).next('#select').find('option:last').val();
Since IDs must be unique, there's no point in doing something like:
jQuery(this).next('#select option:first')
when
jQuery('#select option:first')
would suffice, plus .next() would fail here since it evaluates the siblings of an element and filters on anything you pass, but your filter is what would cause it to not match anything.
Instead, use:
jQuery(".input").click(function () {
var thefirst = jQuery('#select option:first').val();
var thelast = jQuery('#select option:last').val();
if (jQuery(this).is(':checked')) jQuery('#select').val(thelast);
else jQuery('#select').val(thefirst);
});
jsFiddle example
The vanilla javascript alternative for future viewers
(function () {
"use strict";
var inputs = document.getElementsByClassName('input'), input;
for (var i = 0; input = inputs[i]; i++) {
input.addEventListener('click', function (e) {
e.target.nextElementSibling.lastElementChild.selected = e.target.checked;
e.target.nextElementSibling.firstElementChild.selected = !e.target.checked;
}, false);
}
})();
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected>-- choose --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

Ng-Repeat With Changing Variable

Using ng-repeat="i in getNumber(myNumber) track by $index" to repeat a specific number of times which is defined by a select object in HTML.
var number = parseInt($( "#number option:selected" ).text());
$scope.myNumber = number;
$scope.getNumber = function(num) {
return new Array(num);
}
It works perfectly. Now, I want it to update when I change the #number option:selected though. The var number receives this by doing something like this $( "#number" ).change(function() {});, but even when I put the above code block in there, the ng-repeat only changes onload.
How can I use ng-repeat with a changing variable?
Don't use a jQuery event handler, as it the event will not trigger a digest cycle unless you tell it to. You can just supply the select box a ng-model, and a digest cycle will automatically be started on a change of the select to update the bindings.
<select ng-model="myNumber">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div ng-repeat="i in getNumber(myNumber)">
I am at index: {{$index}}
</div>
JSFiddle
You could just watch the iteration number like this:
$scope.iteration = new Array(2);
$scope.$watch('repeat_num',function(new_val) {
if (new_val) {
$scope.iteration = new Array(parseInt($scope.repeat_num));
}
});
HTML
<select ng-model="repeat_num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<ul>
<li ng-repeat="i in iteration track by $index">Value</li>
</ul>

Categories