I have this select input. It will be put in the form multiple times since they also have quantity each.
So the select input will be shown again but i want it to restrict an option that is already selected. Not necessarily to hide the selected input but to prompt an alert whenever the user chooses an option which is already in the form.
<select class="form-control" name="supplier[]" id="supplier[]">
<option value="0">Select Item</option>
#foreach ($items as $item)
<option value="{{{ $item->id }}}">{{{ $item->code}}} - {{{ $item->description}}}</option>
#endforeach
</select>
Build a dictionary of values => counts and when adding to the dictionary check if the key already exists.
Something like this should work:
var counts = {};
$("select[name='supplier[]']").each(function(i, el) {
var val = $(el).val();
if (typeof counts[val] == 'undefined') {
counts[val] = 1;
} else {
alert('value ' + val + ' entered more than once');
}
});
Related
I do have a form with a variable amount of dropdowns I want to check, if something is selected before submit.
What I have is this javascript, but it works for the 1st dropdown only.
var ddl = document.getElementById("status");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "")
{
alert("Machine status must be selected");
return false;
}
for this dropdown (this comes from a loop so I have a variable amount of them within the form)
<select name="mstatus[]" id="status">
<option value="">please select</option>
<option value="status1">ok</option>
<option value="status2">not ok</option>
</select>
Any hint in the right direction, much appreciated. thanks
I would suggest giving the selects you wish to iterate through the same class and use Jquerys .each(). https://api.jquery.com/each/
For the validation I would use a data tag to help you with the alert label
<select class="form-select" data-label="Machine status"></select>
Then the JS code
$('.form-select').each(function(index, element) {
let value = $(element).val();
let label = $(element).data("label");
if (value === "") {
alert(`${label} status must be selected`);
return false;
}
});
Without Jquery you could do.
document.querySelectorAll('.form-select').forEach(function (element, index) {
//do same code here
});
Question Background:
I have two dropdown menus in my app. One is to allow a user to select a Minimum monetary selection and the other a Maximum monetary selection.
The Issue:
If a user selects a value in the Minimum dropdown i.e 4 that is larger than the value select in the Maximum dropdown lets say 3 as then I want to display a popup dialog to the user informing them they cannot do this and then stop the clicked item in the minimum dropdown from being selected.
I can see plenty of example using:
.disable
but I do do not want to 'grey out' any options just validate the clicked items each time and then stop the item from being selected.
Is this possible? Any help would be appreciated.
You can use the "change" event on the select menu to check the value and then decide what to do with this.
document.getElementById('your_dropdown_id').addEventListener('change', myfct);
Where "myfct" is the function testing the value.
like this?
var validate = true;
if ( FirstSelectedValue > SecondSelectedValue ){
alert('first selected value must be higher or equal to second value');
validate = false;
}
//whereever you pass the information to..
if (validate && your other options..){
//continue, first value is lower or equal to second value..
}
A better option would be to only populate the second value when the first value have been selected and only allow valid options.
I would solve this programmatically by handling clicks on the dropdown manually. For example:
$('.dropdown-min').on('click', function(e) {
e.preventDefault();
if($(e.target).val() < $('.dropdown-max').find(":selected").val()) {
$(e.target).attr('selected', 'selected');
}
});
You may do it like this:
JS Fiddle
// grab the two dropdowns with their classname on change event
$('.min-max').on('change', function() {
var $th = $(this),
id = $th.attr('id');
// pass the id and the value to the function
updateMinMax(id, parseInt($th.val()));
})
function updateMinMax(id, v) {
// determine the id of the other dropdown
var otherID = (id == 'minimum') ? 'maximum' : 'minimum',
thisDropdown = $('#' + id),
otherDropdown = $('#' + otherID);
// we need to make sure the other dropdown value is set so we need
// to add this condition otherDropdown.val() != ''
if (id == 'minimum' && otherDropdown.val() != '' && thisDropdown.val() > otherDropdown.val()) {
// if a selected value from minimum dropdown is MORE than
// the selected maximum value
alert('minimum cannot be greater than maximum');
// reset current dropdown selection
thisDropdown.val('');
} else if (id == 'maximum' && otherDropdown.val() != '' && thisDropdown.val() < otherDropdown.val()) {
// if a selected value from maximum dropdown is LESS than
// the selected minimum value
alert('maximum cannot be less than minimum');
thisDropdown.val('');
}
}
select{width:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Min:<select class="min-max" id="minimum">
<option></option><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><option value="6">6</option><option value="7">7</option>
<option value="8">8</option></select><hr>
Max:<select class="min-max" id="maximum">
<option></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><option value="7">7</option><option value="8">8</option>
<option value="9">9</option></select>
I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value
How can I find the index of a dropdown for a given value using jQuery?
Here is my dropdown with three values:
admin
mananger
employee
I'm able to get the index of the selected value like below
var index = $("#mydropdown").find("option:selected").val();
But I need to know the index of manager by passing manager as an argument to a jQuery function to get the index
I tried like this but it's not working
var index = $("#mydropdown").find("manager").val();
I think you need something like this:
js
$("select option[value='manager']").index()
html
<select>
<option value="admin">admin</option>
<option value="manager">mananger</option>
<option value="employee">employee</option>
</select>
fiddle
You can either use :contains or .filter(). I personally prefer .filter():
var index = $("#mydropdown").find(":contains(manager)").val();
//Or
var index = $("#mydropdown").filter(function(){
return $.trim($(this).text()) === "manager";
}).val();
This assume your drop down look like this :
<select>
<option value="1">admin</option>
<option value="2">manager</option>
<option value="3">employee</option>
</select>
Note: If you need to force the user to make a selection use an empty option and then have code check for a value ='0' or an index of zero respectively. I have added an empty option in both implementations below for this purpose.
Implementation #1:
function optionchanged()
{
var i = $("#option1").val();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
}
Assign index to value property in each option allows you greater control over the value returned.
<select id="option1" onchange="optionchanged();">
<option value="0"></option>
<option value="1">Admin</option>
<option value="2">Manager</option>
<option value="3">Employee</option>
</select>
The Console Output looks like this:
Selecting 'Admin' produces:
The Index of option selected is: 1
The Text of option selected is: Admin
Selecting 'Employee' produces:
The Index of option selected is: 3
The Text of option selected is: Employee
Implementation #2:
If you don't want to add the index to value you can reference the index directly in jQuery like this:
function optionchanged()
{
//var i = $("#option1 ").val();
var i = $("#option1 option:selected").index();
var t = $("#option1 option:selected").text();
console.log("The Index of option selected is: " + i);
console.log("The Text of option selected is: " + t);
//alert("Value of option 1 is: " + index);
}
<select id="option1" onchange="optionchanged();">
<option></option>
<option>Admin</option>
<option>Manager</option>
<option>Employee</option>
</select>
The console output will look the same as above.
Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.