focusing on an element after an event is fired - javascript

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().

Related

How should i get previous selected option automatically in dropdown in javascript

In javascript, in a dropdown menu if we select one option and in that dropdown how can I get a dropdown option which had selected previous option automatically on current option (if that current option fails on certain condition).
As you've already discovered, there is no way to get the previously selected value when the dropdown is changed directly from the dropdown itself.
The best option is to store the currently selected value, my preference is via a data- attribute.
So if for example you have a select like the following...
<select>
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
You would include the currently selected value as a data-previousvalue attribute... this would be part of the code that creates the control in the first place...
<select data-previousvalue="1">
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
Then when you change the select, you can check at the current value and if necessary reset it back to that stored one.
In the following example, if you select the third item Three (bad) it will automatically take you back to the previously selected option...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
And if you have jquery available...
$(function(){
$("select").on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you can't add the data attribute to the control at the point of render, then you can also set it on the page load...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// Set the currently selected value into the attribute
dd.setAttribute("data-previousvalue", dd.value);
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you have jquery available to you...
$(function(){
$("select")
.each(function(i,v) {
var $dd = $(this);
$dd.data("previousvalue", $dd.val());
})
.on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
You can do it setting element.val(previousStatus)
// Your changing value should assign on adStatus
// May be its come from database(previous status) or depends on user activity
let adStatus = 'Unfriendly';
$('#AdblockType').val(`${adStatus}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="AdblockType">
<option value="Friendly">Friendly</option>
<option vlaue="Unfriendly">Unfriendly</option>
</select>

Get a value from few drop down

I want to get a value from few dropdown, this few dropdown have a same name in
a table of database.And user can see only one dropdown base on their previous selection, but I can't detect which dropdown is selected by users.So I make something bellow:
$dropvalue = "GetFromJavaascriptBellow" //use to get value from javascript bellow
<select id="dropdown1" name="dropdown1">
<option selected disabled>-- Please select a option --</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="ghi">ghi</option>
</select>
<select id="dropdown2" name="dropdown2">
<option selected disabled>-- Please select a option --</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
<select id="dropdown3" name="dropdown3">
<option selected disabled>-- Please select a option --</option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
</select>
<script>
$('#dropdown1').change(function () {
if ( this.value != '' || this.value != NULL)
{
$dropvalue = this.value //This line is what I can't do (is it possible php variable get value from javascript?)
}
else
{
}
});
$('#dropdown2').change(function () {
if ( this.value != '' || this.value != NULL)
{
$dropvalue = this.value //This line is what I can't do (is it possible php variable get value from javascript?)
}
else
{
}
});
$('#dropdown3').change(function () {
if ( this.value != '' || this.value != NULL)
{
$dropvalue = this.value //This line is what I can't do (is it possible php variable get value from javascript?)
}
else
{
}
});
</script>
My current solution is using ajax to get all of the value from all drop down, and set the default value ='0' to all dropdown, in ajax using if else statement to check which dropdown is not equal to 0 to confirm what is my value and which dropdown is.But this way is conflict with my another function, so I finding another way to did it
Try this. Use querySelectorAll
x=document.querySelectorAll("select.abc");
for(i=0;i<x.length;i++){
x[i].addEventListener("change",function(){
console.log(this.value); // your ajax call or whatever function you want excute
});
}
<select id="dropdown1" name="dropdown1" class="abc">
<option selected disabled>-- Please select a option --</option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="ghi">ghi</option>
</select>
<select id="dropdown2" name="dropdown2" class="abc">
<option selected disabled>-- Please select a option --</option>
<option value="123">123</option>
<option value="456">456</option>
<option value="789">789</option>
</select>
<select id="dropdown3" name="dropdown3">
<option selected disabled>-- Please select a option --</option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</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();
}
})

Multiple select elements - Handle with jQuery when select an option from all of them

I have two select elements with some options. What I want to do is to handle this with jquery so as I can get the values of them only when options have values.
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
If I want to handle with one select element only I use .on('change', function() with select element and it works, but with multiple select element how can I do it.
You should check if selectedIndex is not 0 for all your select elements.
$(document).on('change', 'select', function () {
var allChanged = true;
// check if there is any other select element which was not changed
$('select').each(function () {
if (this.selectedIndex == 0) {
allChanged = false;
}
});
// if all select elements have been changed
if (allChanged) {
alert('BOTH CHANGED');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
Just a side note, use .filter() :
$('select').change(function() {
var m = $(this).siblings('select').addBack();
var n = m.filter(function(){
return $(this).val() == null && $(this)
});
if ( !n.length ) alert('both selected')
});
DEMO

Compare select values and show alert if they match

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.

Categories

Resources