Compare select values and show alert if they match - javascript

I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!

Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>

I used the same class on all the dropdowns and then use only one event handler.
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.

Related

Hide select options based on previous selections

Is it possible to hide options in a select/dropdown with jQuery based on the user's selection from a previous dropdown e.g:
If user is 8 (Age Select/Dropdown), and chooses subject English (Subject Select/Dropdown) then hide Location 2 from (Locations dropdown)?
<select name="age">
<option value="8">8</div>
<option value="9">9</div>
<option value="10">10</div>
<option value="11">11</div>
</select>
<select name="subject">
<option value="eng">English</div>
<option value="maths">Maths</div>
<option value="science">Science</div>
</select>
<select name="subject">
<option value="loc-1">Location One</div>
<option value="loc-2">Location Two</div>
<option value="loc-3">Location Three</div>
</select>
Thank you!
you just need to add change function to your drop-down and according to your requirement you need to add your logic. see below example.
$(document).ready(function(){
$("#age").change(function(){
hideOption();
})
$("#subject").change(function(){
hideOption();
})
})
function hideOption(){
var age=$("#age").val();
var subject=$("#subject").val();
if(age==8 && subject=="Maths"){
$("#location [value='Location Two']").hide();
}
else{
$("#location [value='Location Two']").show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" id='age'>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>
<select name="subject" id='subject'>
<option value="English">English</option>
<option value="Maths">Maths</option>
<option value="Science">Science</option>
</select>
<select name="Location" id='location'>
<option value="Location One">Location One</option>
<option value="Location Two">Location Two</option>
<option value="Location Three">Location Three</option>
</select>
You can do something like below
$(document).on('change', '.age', function(e){
var val = $(this).val();
var subject = $('.subject').find(":selected").val();
if(val == 8 && subject == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
$(document).on('change', '.subject', function(e){
var age = $('.age').find(":selected").val();
var val = $(this).val();
if(age == 8 && val == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" class="age">
<option >select</8>
<option value="8">8</8>
<option value="9">9</8>
<option value="10">10</8>
<option value="11">11</8>
</select>
<select name="subject" class="subject">
<option value="English">English</8>
<option value="Maths">Maths</8>
<option value="Science">Science</8>
</select>
<select name="location" class="location">
<option value="One">Location One</8>
<option value="Two">Location Two</8>
<option value="Three">Location Three</8>
</select>
With jQuery you can use .hide() and .show() to toggle element visibility. First however, you can check if the value of a select (for example age) was changed. Based on the logic you want to have, you can for example check what the value of the change was and do something if it matches a condition.
For example:
$( "#age-select" ).change(function() {
var value = $(this).val();
if(value == 8) {
$("#location-two").hide();
} else {
$("#location-two").show();
}
});
However, notice that I added an id for the "Location Two" option ("location-two") and for the age select element. Also, to make this work properly, you have to fix the values so that they're not all 8 and fix the closing tags of the elements (not ).

How to target outside $(this) in jQuery

I'm trying to use $('.selector').on('change', function(){}) then inside of it, I added each. What I want is to target the current .selector, if the current item is already selected then make it empty so you can select other item; there are multiple <select class='selector'> elements in the DOM. Please see my code below.
$(document).ready(function(){
$('.selector').on('change', function(){
var currentSelect = $(this).val();
if(currentSelect == ''){
$('.selector').each(function(){
if(currentSelect == $(this).val()){
alert("Sorry, you cannot select that item again.");
$(this).val('');
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
You need 2 loops at each change events here.
to get all selected values.
to hide all values already selected from the other <select> elements.
Simple as that.
$(document).ready(function(){
var selected = []; // Global scope array.
$('.selector').on('change', function(){
var currentSelect = $(this).val();
var selected = []; // Array reset
$('.selector').each(function(){
var val = $(this).val();
if(val!=""){
selected.push($(this).val()); // Array fill
}
});
console.log(selected);
$('.selector option').each(function(){
if($.inArray($(this).val(),selected)!=-1){ // If not in array: hide
$(this).hide();
}else{
$(this).show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
<br><br>
<select class="selector">
<option></option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Banana">Banana</option>
<option value="Watermelon">Watermelon</option>
</select>
If I understood your question correctly, this would be the answer. By using $(this), you are applying whatever change to all select elements on the page. You want to do it just for the one that was clicked. For that reason, you should be very careful with $(this) and use $(event.target) instead. Read more about the differences here:
Difference between $(this) and event.target?
$(document).ready(function(){
$('.selector').on('change', function(e){
var currentSelect = $(e.target).val(); // if you need to pass/submit the value somewhere later
$(e.target).attr('disabled', 'disabled');
});
});
Why not simply disable the target element? You can still see what was selected and the user cannot click it again.
This solution is a little bit messy, but it works
$(document).ready(function(){
$(".selector").on("change", function(){
var currentSelect = $(this).val();
$(this).siblings().on("change", function(event){
if(currentSelect == $(this).val()){
$(this).val('')
alert("Sorry, you cannot select that item again.");
}
});
});
});
There isn't really a reason to loop through .each here.
What you can do, is .on('change') create an array of all values of elements with the .selector class. Then once you have that array, check how many instances there are of the element that was just selected. If that number > 1, then that selection has already been made in a different .selector element.
Working Pen:
https://codepen.io/anon/pen/WLvzMM
$(document).ready(function(){
$('.selector').on('change', function(){
// Put the value of all elements with the class of `.selector` into an array
var all = $.map($('.selector'), function (el) { return el.value; });
// Get value of the change that was just made
var currentSelect = $(this).val();
// Get the number of occurences of the value that was just selected
var occurences = $.grep(all, function (elem) {
return elem === currentSelect;
}).length;
// If there is more than one occurence (the one that was just selected), then prevent the selection.
if(occurences > 1){
alert("Sorry, you cannot select that item again.");
$(this).val('');
}
});
});

How to count the number of Form selects that have had values changes in Jquery/Javascript

I have several selects in my form. If one select has had its options changed then it should increase the counter. 5 selects then counter should be 5. Essentially I want to check if all my selects have been selected so I can submit the form. I don't want to use "required".
<div id="firstPanelID"
<div class="form-group input-group">
<label class="fixingLabelAlignmentInner">Transfer Code of Center from which Infant Transferred : </label>
<div class="fixingInputAlignmentInner">
<select id="transferCodePIW" name=transferCodePIW class="form-control" style="height:32px;width:80%;">
<option disabled selected value>SELECT</option>
<option value="13240">13240 - Mowbray Maternity Hospital</option>
<option value="14994">14994 - New Somerset Hospital</option>
<option value="16011">16011 - Tygerberg Hospital</option>
<option value="8005432">8005432 - Khayelitsha District Hospital</option>
<option value="8005433">8005433 - Michell's Plain District Hospital</option>
<option value="8005435">8005435 - Red Cross Children's Hospital</option>
<option value="97777777">97777777 - Birth at Home or in Transit</option>
<option value="">Other</option>
<option value="77777777">N/A</option>
<option value="99999999">Unknown</option>
</select>
</div>
</div>
</div>
I have tried it with the following. The selects may be visible/invisible due to other radio buttons hence the visible. The function works for radio buttons but I can't get it to work for selects.
var sgroups = [];
$('#firstPanelID select:visible:selected').each(function(index, el){
var i;
for(i = 0; i < sgroups.length; i++)
if(sgroups[i] == $(el).attr('name'))
return true;
sgroups.push($(el).attr('name'));
}
);
alert(($('#firstPanelID select:visible:selected').length))
I think the code is self-explanatory.
var counter = 0;
$('select').change(function () {
var o = $(this);
if (!o.hasClass('counted')) {
counter++;
o.addClass('counted');
}
$('#counter').text(counter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
<select>
<option value="2aa">2aa</option>
<option value="2bb">2bb</option>
<option value="2cc">2cc</option>
</select>
<select>
<option value="3aa">3aa</option>
<option value="3bb">3bb</option>
<option value="3cc">3cc</option>
</select>
<div id="counter">
0
</div>
If you want to check if all selects have been checked, assuming each select will have an empty value, you can do this:
function isThereAnyEmptySelection () {
let r = false;
$('select').each(function () {
if ($(this).val() === '') { // or === null, or === undefined, or === '0' etc., depending on context
r = true;
}
});
return r;
}
You can use .one() to attach a single change event to each <select> element, when count is equal to $("selector").length call .off() to remove change event, then perform action, for example, submit <form> element.
let count = 0;
$("select").one("change", function() {
++count;
console.log(count);
if (count === $("select").length) {
$("select").off("change");
// submit form here
console.log(count + " is " + $("select").length)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>

JQuery : Assign null to selected dropdown value

I have two dropdowns. I want the second dropdown, Assign value to be set to null when the specific value which is student from the first dropdown is chosen.
First dropdown:
<select name="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
This is the second dropdown which is hidden, shown only when Reg with value admin is chosen.
<select name="Assign">
<option value="">Choose</option>
<?php
$sql=odbc_exec($conn,'SELECT AssignCd, AssignNm FROM AssignList');
if(odbc_fetch_row($sql))
{
$AssignCd= odbc_result($sql, "AssignCd");
$AssignNm= odbc_result($sql, "AssignNm");
echo "<option value='".$AssignCd."'>".$AssignNm."</option>";
}
?>
</select>
I tried by doing the following but it doesn't work.
Please Help.
if($("#Reg").val("student");) {
$("#AssignCd").val("");
$("#AssignNm").val("");
}
UPDATED:
When Admin is selected, Assign with admin is chosen will be automatically selected. The problem is when I change my option to Student, the supposed value student is chosen is not shown.
How can I make the Assign value of both Admin and Student stay as it is and not jumbled up between them?
This is my code :
fiddle
$(document).ready(function() {
$("#Reg").on("change", function() {
if ($(this).find("option:selected").text() === 'Admin') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').attr("disabled",true).prop("selected", false).wrap('<span>');
$('select[name="Assign"] option[name="admin_assign"]').prop('selected',true);
}
else if ($(this).find("option:selected").text() === 'Student') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').prop('selected',true);
} else {
$("#Assign").hide().attr("disabled"," ");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign" id="Assign">
<option value=" ">Choose</option>
<option name ="student_assign" value="student_assign">student is chosen</option>
<option name ="admin_assign" value="admin_assign">admin is chosen</option>
</select>
$('select[name="Reg"]').on('change', function() {}) this will trigger when you select an option in your select
$(this).find("option:selected").val() == "student" this will see if you have select an option with value "student"
$('select[name="Assign"] option[value="AssignCd"]').text(""); this sets the text of the option with value = AssignCd to empty
This is how far we can go without showing us your generated html for <select name="Assign">
$('select[name="Reg"]').on('change', function() {
if ($(this).find("option:selected").val() == "student") {
$('select[name="Assign"] option[value="AssignCd"]').text("");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign">
<option value="AssignCd">AssignNm</option>
</select>
Update
There is no need to use .wrap() as far as i can see, use .hide() / .show() look at the example below.
$(document).ready(function() {
$("#Reg").on("change", function() {
if ($(this).find("option:selected").text() === 'Admin') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').attr("disabled", true).prop("selected", false).hide();
$('select[name="Assign"] option[name="admin_assign"]').prop('selected', true);
} else if ($(this).find("option:selected").text() === 'Student') {
$('select[name="Assign"] option[name="student_assign"]').attr("disabled", false).prop("selected", true).show()
$('select[name="Assign"] option[name="student_assign"]').prop('selected', true);
} else {
$("#Assign").hide().attr("disabled", " ");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign" id="Assign">
<option value=" ">Choose</option>
<option name ="student_assign" value="student_assign">student is chosen</option>
<option name ="admin_assign" value="admin_assign">admin is chosen</option>
</select>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
First of all #<selector> is used to select Dom elements which have an id <selector>. You cannot access them with the name attribute and id selector.
As for your issue. you need to use the on change event of the first drop down to decide the visibility of the second drop down.
<select name="Assign" id="Assign">
<option value="">Choose</option>
....
....
$('#Assign').hide(); // first hide it so they cannot see it
$(document).on('change', '#Reg', function(e){
if($(this).val()=='admin'){
$('#Assign').show();
}else{
$('#Assign').val('').hide();
}
})

focusing on an element after an event is fired

I want to display an alert message if the user does not select any item in the dropdown then focus that dropdown. I want to do this in all dropdowns with the class "select".
$("#submit").click(function(event) {
if (!$(".select").val()) {
alert("please select one");
event.preventDefault();
$(".select").focus();
}
});
Now, this works fine for one dropdown, but when there are multiple dropdowns, it focuses on the very last, not the particular dropdown.For example, consider an html page with three dropdowns.
<select class="select" id="usertype">
<option value="">Select one</option>
<option value="guest">Guest</option>
<option value="admin">Admin</option>
</select>
<select class="select" id="gender">
<option value="">Select one</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select class="select" id="languages">
<option value="">Select one</option>
<option value="c++">c++</option>
<option value="c">c</option>
</select>
If I selected some items in both languages and gender but select nothing from usertype ("Select one"'s value is ""), the alert message is displayed, but the focus goes to languages, instead of usertype.
What should I do to focus on the unselect dropdown (or the first unselected if the user did not choose items from many dropdowns)?
How about this:
$("#submit").click(function(event) {
if (!$(".select").val()) {
alert("please select one");
event.preventDefault();
$(".select[selectedIndex=0]").focus();
}
});
You can do it with $.each,
$("#submit").click(function(event) {
$(".select").each(function(){
if (!$(this).val()) {
alert("please select one");
event.preventDefault();
$(this).focus();
return false;
}
});
});
Given the updated HTML, and in the face of some rampant unexplained down-voting, I'd suggest the following:
// binding the anonymous function of the 'click'
// method as the event-handler for clicks on the
// element with the id of 'submit':
$("#submit").click(function (event) {
// caching all the elements with the class of
// 'select':
var selects = $('.select'),
// filtering those cached elements elements,
// retaining only those for whom the assessment
// provided to filter()'s anonymous function
// returns a value of true, or is 'truthy':
hasNoValue = selects.filter(function () {
// here we're checking that the current
// select has a value of '' (empty string):
return this.value === '' &&
// and that its currently selected <option>
// (this.options is a collection of the
// <option> elements within the current
// <select> element, and this.selectedIndex
// is the index of the selected <option>
// in the options collection) has the
// text of 'Select one'
// (String.prototype.trim() removes leading
// and trailing white-space from a supplied
// string):
this.options[this.selectedIndex].text.trim() === 'Select one'
});
// if the hasNoValue collection of <select> elements has a length
// other than (the 'falsey') 0, then we enter the 'if':
if (hasNoValue.length) {
// preventing the default action of the click event:
event.preventDefault();
// selecting the first element from the collection
// held within hasNoValue, and focusing that one:
hasNoValue.eq(0).focus();
}
});
$("#submit").click(function(event) {
var selects = $('.select'),
hasNoValue = selects.filter(function() {
return this.value === '' && this.options[this.selectedIndex].text.trim() === 'Select one'
});
if (hasNoValue.length) {
hasNoValue.eq(0).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select" id="usertype">
<option value="">Select one</option>
<option value="guest">Guest</option>
<option value="admin">Admin</option>
</select>
<select class="select" id="gender">
<option value="">Select one</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select class="select" id="languages">
<option value="">Select one</option>
<option value="c++">c++</option>
<option value="c">c</option>
</select>
<button id="submit">submit button</button>
External JS Fiddle demo, for experimentation and development.
References:
JavaScript:
HTMLOptionElement.
HTMLSelectElement.
String.prototype.trim().
jQuery:
click().
eq().
filter().
focus().

Categories

Resources