Check if dropdown's selected option is not the first with JavaScript - javascript

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.

Related

How to check multiple select fields if something is selected

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
});

How do you populate an option value using jQuery?

I am trying to populate a form option value if it's attribute quantity equals zero.
My goal is to add the a message to the current option value
My html is:
<select class="valid">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
So far I've tried the following in jQuery but it's not working:
if($(this).attr('quantity') == '0') {
$(this).append('<span>message</span>');
}
If you don't care about preserving the original message, than you can simply say $(this).text("message"). Leave out the <span> since it cannot be rendered inside of an <option> element anyway.
if($(this).attr('quantity') == '0') {
$(this).text('message');
}
If you want to preserve the original message, you have a couple options. One would simply be to append the new message to the original, however, it may get tricky to remove it later, so I would suggest having some sort of delimiter so you can easily identify the original vs the appended message, like so:
var $option = $(this);
if($option.attr('quantity') == '0') {
$option.text($option.text().trim() + ' (message)');
}
Then, to remove the message, you can do something like this:
$option.text($option.text().slice(0, $option.text().indexOf('(')).trim());
You can populate the option with like this,
$(document).ready(function () {
$('.valid').on('change', function () {
if ($(this.options[this.selectedIndex]).attr('quantity') == 0) {
$(this.options[this.selectedIndex]).find('span').remove();
$(this.options[this.selectedIndex]).append('<span>Message</span>')
}
});
});
JSFIDDLE
I'm not entirely sure of what you're trying to achieve from your question, but you cannot add html elements to an option element. You can however change the text as follows:
$(document).on('change', '.valid', function(){
var selected = $('.valid > option:selected');
if(selected.attr('quantity') == '0'){
selected.text('something else');
}
});
if you wanted to append an error you could do so by using jQuery append() or concatenating with the original value. Alternatively if you wanted it as validation outside of the select box, you could simply assign to the value of a div by replacing the line inside of the if statement.
<select class="valid" onchange="quality(this.options[this.selectedIndex].getAttribute('quantity'));">
<option disabled="disabled" selected="selected" value="">Select Bar</option>
<option value="1" quantity="99">value 1 </option>
<option value="2" quantity="0">value 2 </option>
</select>
<span id="msg"></span>
<script type="text/javascript">
function quality(val) {
if(parseInt(val) == 0){
document.getElementById("msg").innerHTML = "Message";
}
}

ng-model select dropdown update - angular

Basically i have a select dropdown
<select class="form-control" id="ursel"
ng-change="changeVal()"
ng-options="a for a in RatedVoltage" data-ng-model="TechCharacters.selectedUr">
<option value="" selected="selected">{{globalLangResource.SelectAny}}</option>
</select>
So on change of this select, have results reflecting to another select
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
}
}
The 2nd dropdown looks like this
<select class="form-control" id="udsel"
ng-change="setUd();"
ng-options="a for a in ud" data-ng-model="TechCharacters.InsulVolt">
<option value="" ng-if="false"></option>
</select>
Now i have a submit button, on submit,i am getting the main object.
console.log(TechCharacters);
Here i am not getting TechCharacters.InsulVolt value. it is showing empty.
If i have made change is the 2nd dropdown, the model is updated. until then i am not getting the changed model from 1st dropdown
Basically i want all the ng-model values inside form even it is changed or not.
if you want the first object of second dropdown on change of first one. change code to .
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
viewModel.TechCharacters.InsulVolt=$rootScope.ud[0]
}
}
hope it will help you
You can actually do this. This will work.
<select data-ng-model="TechCharacters.selectedUr"
<option ng-selected="{{obj == TechCharacters.selectedUr}}" value="{{obj}}" ng-repeat="(key,value) in RatedVoltage">
</select>
Basically you are doing ng-selected and comparing the ng-model value with that of the ng repeat value, and the selected value will be shown.

Select and Deselect not working in IE9?

I have a dropdown <select> element to select states from the list of 50 states, I select the 1st value, save it, and show the value in DOM. I changed and select to the 5th value, saving it shows the value updates in DOM. Now back i am selecting the 2nd Value, and saving it. It's not saving the value in DOM and it's showing the previous selected 5th value. I Checked with different values, and found that, after selecting any higher index value, selecting back, lower values are not affecting in DOM, and hence i am not getting the correct values in POST.
This is the function i am calling on change.
function updateDOM(inputField) {
var elementId = inputField;
if (inputField.type == "select-one") {
var prev_select = inputField.selectedIndex;
$('#'+inputField.id+' option').each(
function() {
$(this).removeAttr('selected');
}
);
document.getElementById(elementId.id).selectedIndex = prev_select;
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
document.getElementById(elementId.id).value
= document.getElementById(elementId.id).options[prev_select].value;
}
The HTML
<select id="abc" name="abc" onchange="javascript:updateDOM(this);" class="required" >
<option name="" value="" title="null" selected ></option>
<option name="AK" value="Alaska" title="null" >Alaska</option>
<option name="AL" value="Alabama" title="null" >Alabama</option>
<option name="AR" value="Arkansas" title="null" >Arkansas</option>
<option name="AZ" value="Arizona" title="null" >Arizona</option>
</select>
First of all, why don't you use ":selected" selector of jQuery, which you are using anyway? Also, why are you using jQuery only once?
I would recommend doing it in jQuery-style (sorry, I'm not quite sure what you are trying to do exactly in your code):
http://jsfiddle.net/msLXt/1/
P.S. What is the difference between these conditions?
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}

Specifying the values of two elements in an If Statement by (separate) classes and/or data-values

My apologies for writing such a lengthy question but I was asked to clarify several details about the function
What would be the correct way to add another element to these If Statements if I want to call it by class or data-name (or another method which doesn't require creating separate If Statements for each element which will utilize it)?
The function is used on pairs of 2 interconnected elements (who's classes are complaint and ranking). The name of the 1rst Element matches the data-name of the 2nd Element, and since the function already identifies data-name of "ranking" maybe it can say that the name of the 1rst element = data-name of the 2nd element?
if ($(this).val() == 1 && !$(this).data("decrease_priority1")) { ... }
if ($(this).data("decrease_priority1") && $(this).val() != 1) { ... }
Here's what I'm trying to do:
1rst If Statement - Set element if values are: ".complaint" = "Too_small" AND ."ranking" = "1"
2nd If Statement - Update element if values are: ".complaint" = "Too_small" OR ."ranking" = "1"
This 2nd element is the value of the select tag under the .complaint class, however there are several element with the same class so I need a way to specify which one it is. I'm trying to avoid using ID's because there are 25 Select elements (so well over 100 combinations).
Method I've Tried
This doesn't work properly (It doesn't accept input unless the 1rst pair (Shoulders) is selected before the 2nd pair (Waist))
if ($(".complaint select").val() === "Too_small" && $(this).val() == 1 && !$(this).data("increase_priority1"))
{ ... }
if ($(this).data("increase_priority1") && ($(this).val() != 1 || $(".complaint select").val() != "Too_small"))
{ ... }
What the function does
The purpose of this Change function is to take all the complaint names selected (i.e. Shoulders, Waist) and group them into actions (i.e. increase or decrease) by ranking, so there are different functions that get called for the various combinations - in this case "Too_small" AND "1". This snippet adds values to "increase_priority1" when the user selects both a complaint and ranks the importance level of the issue, and removes the value when the user changes either element.
If you want to see this in context, I created 2 fiddles. The first is of the existing script http://jsfiddle.net/chayacooper/vWLEn/171/ and the second is a working example of what I'm trying to do but it uses ID's to do so http://jsfiddle.net/chayacooper/gYtZw/61/
Javascript
var $increase_priority1 = $(".increase_priority1");
// variables for other issues and priority levels go here
$(".ranking").change(function () {
var name = $(this).data("name"); // Gets data-name of ".ranking"
// Sets & Unsets increase_priority1
// I need to change this to state If values are "Too_small" AND "1" AND (...)
if ($(this).val() == 1 && !$(this).data("increase_priority1")) {
//rank is 1, and not yet added to priority list
$("<option>", {text: name, val: name}).appendTo($increase_priority1);
$(this).data("increase_priority1", true); // flag as a priority item
}
//If either ranking or complaint value changes
if ($(this).data("increase_priority1") && $(this).val() != 1) {
//is in priority list, but now demoted
$("option[value=" + name + "]", $increase_priority1).remove();
$(this).removeData("increase_priority1"); // no longer a priority1 item
}
// Similar If Statements go here to set & unset elements for other priority types
});
If the value of $increase_priority1 is "Shoulders", complaint was Shoulders too small (select name=Shoulders value=Too_small), and it was assigned a level 1 priority (select class="ranking shoulders" value=1).
HTML
<label>To Increase - 1rst Priority
<select name="modify_increase_1rst[]" class="increase_priority1" multiple></select></label>
<span class="complaint"><label>Shoulders</label>
<select name=Shoulders><option value="null">Select</option><option value="Too_small">Too Small</option><option value="Too_big">Too Big</option><option value="Too_expensive">Too expensive</option>
</select></span>
<label>Ranking</label>
<select name="importance_bother_shoulders" class="ranking shoulders" data-name="Shoulders">
<option value="Null">Select</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>
I'm finding your question a bit confusing, but
$(".ranking, .complaint select")
referring to two different elements there seems a bit scary with all of your use of $(this) within the function, as well as the fact that from within the selected .complaint select you've brought in to the jQuery factory, you're again calling all
$('.complaint select')
in your first if statement. That jQuery factory call pulls in an array of all of your .complaint select elements, so, checking .val() on it probably has undesired results. I'm sure you intend to check $(this).val() instead, or at least target only one .complaint select element, and not the entire array. If you want to check the entire array, you should investigate using .each().
More along the lines of what you're trying to do? Again, it's very hard to decipher what you're actually trying to do here between confusion about the code (it's very haphazardly) and confusion about the application purpose itself. This is moreso conceptual to show you how to separate these elements. You need to modularize them, they shouldn't share any concerns:
$(".complaint select").change(function() {
var name = $(this).data("name"); //get priority name
// Why was it && before? It's either Too_small or 1 or "Too_small" == 1 so
// you don't have to check twice for the same thing
if (($(this).val() === "Too_small" || $(this).val() == 1)
&&!$('.ranking').data("increase_priority1")) {
//rank is 1, and not yet added to priority list
$("<option>", {text:name, val:name}).appendTo($increase_priority1);
// .complaint select does not contain a data "increase priority"
//$(this).data("increase_priority1", true); //flag as a priority item
});
$('.ranking').change(function(){
if ($(this).data("increase_priority1") &&
($(this).val() != 1)) {
$(".complaint select").each(function(){
if($(this).val() != "Too_small"){
//is in priority list, but now demoted
$("option[value=" + name + "]", $increase_priority1).remove();
$(this).removeData("increase_priority1"); //no longer a priority item
}
}
});
Special thanks to #Lorax for helping me figure this out :-)
I've included the final code below and created a working example of it at http://jsfiddle.net/chayacooper/6YnQd/42/
Javascript
$('.complaint select.complaintOpt').change(function() {
var $container = $(this).parent(),
$item = $container.find('.complaintItem'),
itemId = $item.attr('id'),
itemVal = $item.val(),
itemText = $item.find('option[value=' + itemVal + ']').html(),
rank = $container.find('.complaintRanking').val();
// Ignore if not a complete complaint
if((itemVal == 'Null') || (rank == 'Null')) {
return;
}
// Remove any existing complaint
$('select.priorityIssue option.' + itemId).remove();
var $selectedOption = $item.find('option:selected');
var targetBase = '';
if($selectedOption.hasClass('goal-increase')) {
targetBase = '#priorityIncrease';
}
else if($selectedOption.hasClass('goal-decrease')) {
targetBase = '#priorityDecrease';
}
if(targetBase != '') {
// Add new complaint
$(targetBase + rank + 'Issues')
.append($('<option>' + $item.attr('name') + '</option>').addClass(itemId));
}
});
HTML
<label>To Increase </label><br/>
<label for="priorityIncrease1Issues">First Priority</label>
<select name="modify_increase_1rst[]" id="priorityIncrease1Issues" class="priorityIssue" multiple></select>
<label for="priorityIncrease2Issues">Second Priority</label>
<select name="modify_increase_2nd[]" id="priorityIncrease2Issues" class="priorityIssue" multiple></select>
<br/>
<label>To Decrease </label><br/>
<label for="priorityDecrease1Issues">First Priority</label>
<select name="modify_decrease_1rst[]" id="priorityDecrease1Issues" class="priorityIssue" multiple></select>
<label for="priorityDecrease2Issues">Second Priority</label>
<select name="modify_decrease_2nd[]" id="priorityDecrease2Issues" class="priorityIssue" multiple></select>
<br />
<div class="complaint">
<label for="shoulders">Shoulders</label>
<select name=Shoulders id="shoulders" class="complaintOpt complaintItem">
<option value="Null">Select</option>
<option value="too_big" class="goal-decrease">Too Big</option>
<option value="too_small" class="goal-increase">Too Small</option>
</select>
<label for="shouldersRanking">Ranking</label>
<select name="importance_bother_shoulders" id="shouldersRanking" class="complaintOpt complaintRanking">
<option value="Null">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>

Categories