How to check multiple select fields if something is selected - javascript

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

Related

Select Drop down Form Validation (Display text)

I am trying to validate a form.
What I am trying to do is validate the form by validating the Option display text not the option value, since the option values are int
Example:
<option value="selectcard">Please select</option>
If user clicks submit the form should validate if the option display says Please Select
regardless of what the option value is.
Code which is not working
function fun(){
$('#cardtype').change(function () {
var sel = $('option:selected', this).text();
if (sel == "Please select") {
$('.showotherpDescription').show();
} else {
}
});
}
Not working: http://jsfiddle.net/f5hxpo7g/2/
Also including the regular working example for validating the form based on option value
Validates Based on option value http://jsfiddle.net/f5hxpo7g/1/
Please let me know what i am doing wrong.
Thanks in advance.
Your function should be like this:
function fun()
{
var ddl = document.getElementById("cardtype");
var valor = ddl.options[ddl.selectedIndex].text;
if (valor == "--- Please select ---")
{
alert("Please select a card type");
}
}
Working fiddle:http://jsfiddle.net/robertrozas/XFtBD/169/
I fixed it, you should use this JS:
$(function () {
$('#subbutton').click(function () {
if ($('#cardtype option:selected').text() === "Please select")
{
alert("PLEASE SELECT");
}
});
});
And remove onclick="..." from the button, you don't need it. Also add id="subbutton.
Here's the working JSFiddle.
I checked out the jsfiddle you referenced and modified it slightly to make it work, you can see it here.
The issue with the code you provided is, IMO:
An issue with the purpose of your function (validation) and the event you're subscribing the code to (the combo selection changed event)
The way you're obtaining the text from the currently selected option, you should create the selector based on the element that contains the options, otherwise, if you have more than 1 combo in your page, you will get lots of values (one for each selected option).
Check out the code in the jsfiddle i provided and let me know if you need more information.
For reference, here is the code i used:
HTML:
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select>
<input type="button" onclick="fun()" value="click here">
JS:
function fun(){
var cmb = document.getElementById('cardtype');
var sel = cmb.options[cmb.selectedIndex].text;
if (sel == "--- Please select ---") {
alert('Please select a different option');
//$('.showotherpDescription').show();
} else {
}
}
}

jQuery: If user changes select to specific option then change different input value

I have a select box like so:
<select id="update_type_picker" name="update_type_picker">
<option value="play">Played</option>
<option value="play">playing</option>
<option value="want">Want</option>
<option value="rating">Rate</option>
</select>
And an input like this:
<input id="playing" name="playing" type="hidden">
And I'm trying to make this jquery work:
$(document).ready(function () {
$("select#update_type_picker").change( function() {
var text = this.text;
if (text = "playing") {
$("input#playing").attr('value', '1');
} else {
$("input#playing").attr('value', '');
}
});
});
I need to use text (not value) because two of the values are the same. With the jquery above the input value changes to 1 regardless of which option I choose. How can I make this work they way I need it to? Thanks!
You have to use:
var text = $(this).find("option:selected").text();
And as mentioned in a comment, you have to use == or === to compare strings in the if, not =.

Create select input with button in options

It's possible to create a select input with a button or a link inside the options? I'd like to use it to list some values, and to have the option with a button to "Create Value" inside the options. I don't know if this is possible. I tried it with a href, but it treat it as text.
This would be the ideal scenario:
<select name="things">
<option value="1">Thing One</option>
<option value="2">Thing Two</option>
<option value="3">Thing Three</option>
<option value=""><button>New Thing</button></option>
</select>
I've search, but with no luck. Does somebody knows an jQuery plugin or something like might work?
Here's a simple implementation:
$('select[name=things]').change(function() {
if ($(this).val() == '')
{
var newThing = prompt('Enter a name for the new thing:');
var newValue = $('option', this).length;
$('<option>')
.text(newThing)
.attr('value', newValue)
.insertBefore($('option[value=]', this));
$(this).val(newValue);
}
});
Of course, this could be done better, and more cleanly, but it's a start.
Demonstration
After reading your comments, it appears you simply want to redirect the user to another form when they select a given option. In that case, you can simply do this:
$('select[name=things]').change(function() {
if ($(this).val() == '')
{
window.location.href = 'CreateThingForm'; // Replace with the actual URL
}
});
You shouldn't do it this way, don't put button inside option.
alternatively you can :
<select name="things" onchange="checkAndAddOption(this)">
or
<select name="things" onclick="checkAndAddOption(this)">
.
.
.
</select>
<script>
function checkAndAddOption(selectElement) {
if (selectElement.value === "") {
var opt = document.createElement('option');
opt.value = 'newVal';
opt.innerHTML = 'textToDisplay';
selectElement.appendChild(opt);
}
}
</script>

Check if dropdown's selected option is not the first with 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.

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories