select2 plugin after event remove item from options list - javascript

I use the selec2 plugin and I want to remove an option from my main option list. When I click on "x" button by this code, it removes just from plugin list. After close/open it recovers.
Can anyone help me?
jsfiddle
HTML:
<select id="select">
<option value="Provider 1">Provider 1</option>
<option value="Provider 2">Provider 2</option>
<option value="Provider 3">Provider 3</option>
<option value="Provider 4">Provider 4</option>
<option value="Provider 5">Provider 5</option>
</select>
JS:
function format(state) {
if (state.id == null) {
return state.text;
}
var $option = $("<span></span>");
var $preview = $('<span class="select2-item-remove">×</span>');
$preview.on('mouseup', function (e) {
e.stopPropagation();
});
$preview.on('click', function (e) {
$(this).closest('li').remove();
});
$option.text(state.text);
$option.append($preview);
return $option;
}
$("#select").select2({
templateResult: format,
escapeMarkup: function (m) { return m; }
});

You have to remove also the option element.
So here is your fiddle updated:
https://jsfiddle.net/beaver71/0wz9m7gz/
$(document).ready(function () {
function format(state) {
if (state.id == null) {
return state.text;
}
var $option = $("<span></span>");
var $preview = $('<span data-opt="'+state.element.id+'" class="select2-item-remove">×</span>');
$preview.on('mouseup', function (e) {
e.stopPropagation();
});
$preview.on('click', function (e) {
$(this).closest('li').remove();
var opt = $(this).data('opt');
$("#"+opt).remove();
});
$option.text(state.text);
$option.append($preview);
return $option;
}
$("#select").select2({
templateResult: format,
escapeMarkup: function (m) { return m; }
});
});
.select2-results__option {
position: relative;
}
.select2-item-remove {
position: absolute;
right: 9px;
top: 5px;
z-index: 1100;
z-index: 9999;
cursor: default;
display: block;
font-weight: bold;
font-size: 15px;
padding: 0 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.full.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.css" rel="stylesheet"/>
<select id="select" multiple="multiple" style='width:300px'>
<option id="opt1" value="Provider 1">Provider 1</option>
<option id="opt2" value="Provider 2">Provider 2</option>
<option id="opt3" value="Provider 3">Provider 3</option>
<option id="opt4" value="Provider 4">Provider 4</option>
<option id="opt5" value="Provider 5">Provider 5</option>
</select>

Related

HTML multi select opt group select box always scroll to top

I have implemented HTML opt group select box.
After selecting a top element and scroll down, again when I am selecting an item which is located at the bottom of the select box.scroll position is automatically changing to top.this is not good in terms of usability.I spent lot of times to fix this issue.but still i couldnt.
https://jsfiddle.net/nsandaruwa/tj1f2gyx/5/
$('option').mousedown(function(e) {
e.preventDefault();
var originalScrollTop = $(this).parent().scrollTop();
console.log(originalScrollTop);
$(this).prop('selected', $(this).prop('selected') ? false : true);
var self = this;
$(this).parent().focus();
setTimeout(function() {
$(self).parent().scrollTop(originalScrollTop);
}, 0);
return false;
});
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="" class="form-control select-checkbox" size="5">
<optgroup label="One">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
<optgroup label="Two">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
<optgroup label="Three">
<option>Dog</option>
<option>Cat</option>
<option>Hippo</option>
<option>Dinosaur</option>
<option>Another Dog</option>
</optgroup>
</select>
Better?
$('option').mousedown(function(e) {
e.preventDefault();
const that = this;
$(this).prop('selected', $(this).prop('selected') ? false : true);
setTimeout(function() { that.scrollIntoView() },10)
return false;
});
body {
padding: 15px;
}
.select-checkbox option::before {
content: "\2610";
width: 1.3em;
text-align: center;
display: inline-block;
}
.select-checkbox option:checked::before {
content: "\2611";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="" class="form-control select-checkbox" size="5">
<optgroup label="One">
<option>Dog 1</option>
<option>Cat 1</option>
<option>Hippo 1</option>
<option>Dinosaur 1</option>
<option>Another Dog 1</option>
</optgroup>
<optgroup label="Two">
<option>Dog 2</option>
<option>Cat 2</option>
<option>Hippo 2</option>
<option>Dinosaur 2</option>
<option>Another Dog 2</option>
</optgroup>
<optgroup label="Three">
<option>Dog 3</option>
<option>Cat 3</option>
<option>Hippo 3</option>
<option>Dinosaur 3</option>
<option>Another Dog 3</option>
</optgroup>
</select>

How to add and remove <option> with <optgroup> from box A to box B in Safari?

This question is already asked here and it's perfectly answered, but the problem is it doesn't work properly in Safari like it does in Chrome. In Safari, neither optgroup nor option support display: none.
Is there any way to get it to work like it does in Chrome?
Here is codepen Snippet
$.each($('#u-address > optgroup'), function() {
$(this).clone().empty().appendTo('#m-address');
});
myOgVisibility();
//for dblclick
$('#u-address').dblclick(function() {
$.each($('#u-address option:selected'), function() {
var og = $(this).parent().attr('class');
$(this).remove().appendTo('#m-address .' + og);
$(this).removeAttr('selected');
});
myOgVisibility();
});
$('#m-address').dblclick(function() {
$.each($('#m-address option:selected'), function() {
var og = $(this).parent().attr('class');
$(this).remove().appendTo('#u-address .' + og);
$(this).removeAttr('selected');
});
myOgVisibility();
});
function myOgVisibility() {
$.each($('.showUniOgrp > optgroup'), function() {
if ($(this).html().trim() === "") {
//$(this).detach();
//$(this).css({'display': 'none'});
//$(this).attr('disabled', 'disabled').hide();
$(this).css({
'height': '0px !important',
'display': 'none'
});
} else {
//$(this).appendTo('#m-address');
//$(this).css({'display': 'block'});
//$(this).removeAttr('disabled').show();
$(this).css({
'height': 'auto',
'display': 'block'
});
}
});
}
select {
display: inline-block;
width: 30%;
height: 200px;
border-radius: 5px;
overflow: hidden;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="u-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="u-address">
<optgroup class="og-swe" data-opt="qq" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup class="og-ger" data-opt="qq" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</optgroup>
<optgroup class="og-ita" data-opt="qq" label="Italian Cars">
<option value="ferrari">Ferrari</option>
<option value="lamborghini">Lamborghini</option>
</optgroup>
</select>
</div>
<div class="my-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="m-address">
</select>
</div>
You're gonna need a third select with all the optgroups and options which is hidden. You can use it in different ways to achieve what you want but here's one way:
You have all the info in the hidden select (#h-address) and once an option is selected you add a class to it (.slctd) and if unselected you remove the class. Then populate the two visible selects and remove undesired parts from each.
$.each($('#h-address > optgroup'), function() {
$(this).clone().appendTo('#u-address');
});
$('#u-address').dblclick(function() {
$.each($('#u-address option:selected'), function() {
$('#hidden-fields option[value=' + $(this).val() + ']').addClass('slctd');
showFields();
});
});
$('#m-address').dblclick(function() {
$.each($('#m-address option:selected'), function() {
$('#hidden-fields option[value=' + $(this).val() + ']').removeClass('slctd');
showFields();
});
});
function showFields() {
$('#u-address').empty();
$('#m-address').empty();
$.each($('#h-address > optgroup'), function() {
$(this).clone().appendTo('#u-address');
$(this).clone().appendTo('#m-address');
});
$('#u-address option.slctd').remove();
$('#m-address option:not(.slctd)').remove();
$.each($('.showUniOgrp > optgroup'), function() {
if ($(this).html().trim() === "") {
$(this).remove(); //or detach()
}
});
}
select {
display: inline-block;
width: 30%;
height: 200px;
border-radius: 5px;
overflow: hidden;
float: left;
}
#hidden-fields {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="u-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="u-address"></select>
</div>
<div class="my-address-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="m-address"></select>
</div>
<div id="hidden-fields">
<select size="15" multiple="multiple" class="showUniOgrp" id="h-address">
<optgroup class="og-swe" data-opt="qq" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup class="og-ger" data-opt="qq" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</optgroup>
<optgroup class="og-ita" data-opt="qq" label="Italian Cars">
<option value="ferrari">Ferrari</option>
<option value="lamborghini">Lamborghini</option>
</optgroup>
</select>
</div>
Haven't tested on Safari, but it should work.

Hide selected option from another select box

Edit, yes I am aware of this question but that answer is not completely working for my case
I'm looking for a solution for this case
When a user selects an option from one select box the option should be hidden for the other select boxes.
When a selected option changes or is removed (select a blank option) the previously selected option should become available again to the other select boxes.
The problem with my current code:
When an option changes, the previous option is not "released" to the other select boxes so they can not use it again until the page reloads.
Basically, results in previously selected options are dissapearing from other select boxes.
I included a fiddle so you can see it for youself.
$(document).ready(function() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
var prevValue = $(this).data('previous');
$('.update-select').not(this).find('option[value="' + prevValue + '"]').show();
var value = $(this).val();
if (value) {
$(this).data('previous', value);
console.log($(this).data('previous', value));
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
It's as simple as this. Just .show() all the option's and reinitialize the select's using your previous code.
$(document).ready(function() {
function intializeSelect() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
};
intializeSelect();
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
$('.update-select').find('option').show();
intializeSelect();
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
This is my solution:
$(document).ready(function() {
$(document).on('change', '.update-select', function(e) {
$('option').show();
var selectedOptionsGlobal = [];
$.each($('.update-select'), function(key, select) {
var selectedOptionValue = $(select).val();
if (selectedOptionValue !== "") {
selectedOptionsGlobal.push(selectedOptionValue);
}
});
for (var i = 0; i < selectedOptionsGlobal.length; i++) {
$('option[value="'+selectedOptionsGlobal[i]+'"]').hide();
}
});
});

tidying up jQuery method for validating form

I am validating a form using jQuery.
It is working perfectly, but I just feel the code is quite "bulky". There is a lot of if statements being used to achieve this logic in the app.sendForm.init() function. I think this could be tidied and any advice here would be greatly appreciated. Perhaps I should be using a switch statement instead?
Is there another approach I should take to tidy up this code, or do I just have to accept it is going to be quite longwinded?
I have also posted the question here where more be a more appropriate forum for this type of question.
"use strict";
var app = app || {};
(function(){
app.initialize = {
init: function() {
app.sendForm.init();
}
};
app.sendForm = {
init: function(){
$("#entry").submit(function( event ) {
var userEmail = $("#email"),
userName = $("#first_name"),
userLastName = $("#last_name"),
date = $("#birth_day"),
month = $("#birth_month"),
year = $("#birth_year"),
countryName = $("#country");
app.validation.dateOfBirth(date, month, year);
if(!app.validation.empty(date) ||!app.validation.empty(month) ||!app.validation.empty(year) || !app.validation.empty(countryName) || !app.validation.email(userEmail) || !app.validation.empty(userName) || !app.validation.empty(userLastName)){
event.preventDefault();
alert("didnt send")
if(!app.validation.email(userEmail)) {
userEmail.addClass('invalid');
} else {
userEmail.removeClass('invalid');
}
if(!app.validation.empty(userName)) {
userName.addClass('invalid');
} else {
userName.removeClass('invalid');
}
if(!app.validation.empty(userLastName)) {
userLastName.addClass('invalid');
} else {
userLastName.removeClass('invalid');
}
if(!app.validation.empty(countryName)) {
countryName.addClass('invalid');
} else {
countryName.removeClass('invalid');
}
if(!app.validation.empty(date)) {
date.addClass('invalid');
} else {
date.removeClass('invalid');
}
if(!app.validation.empty(month)) {
month.addClass('invalid');
} else {
month.removeClass('invalid');
}
if(!app.validation.empty(year)) {
year.addClass('invalid');
} else {
year.removeClass('invalid');
}
if(!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
} else {
$('.terms-con').removeClass('invalid');
}
} else {
$("#thank-you").css("display", "block");
alert("sent")
}
});
}
};
/*
* Validation
*/
app.validation = {
email: function(id) {
// Regex, use this to validate the Email. It return true or false.
var emailVal = id.val(),
re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(emailVal);
},
empty: function(id) {
// Use this to validate the Password. Checks if value is empty. It return true or false.
var elementVal = $.trim(id.val());
if(elementVal.length > 0)
return true;
},
dateOfBirth: function(date, month, year) {
var forbiddenAge = 14;
var DOB = date + " " + month + " " + year;
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(age < forbiddenAge){
alert("you are under 14");
}
}
};
app.docOnReady = {
init: function() {
app.initialize.init();
}
};
$(document).ready(app.docOnReady.init);
})(jQuery);
body {
background-color: #fff;
color: #000;
font-family: 'Arial', sans-serif;
margin: 0;
}
#entry {
font-family: 'Arial', sans-serif;
max-width: 400px;
margin: 0 auto;
}
#entry input,
#entry select {
display: block;
margin-bottom: 10px;
}
#entry label {
padding-bottom: 5px;
}
#entry #birth_day,
#entry #birth_month,
#entry #birth_year {
display: inline-block;
}
#entry input[type=submit] {
display: block;
border: 1px solid #1e1e1e;
text-transform: uppercase;
font-family: 'Arial', sans-serif;
font-size: 16px;
font-weight: 400;
text-transform: capitalize;
text-decoration: none;
color: #fff;
line-height: 20px;
letter-spacing: .5px;
max-width: 150px;
height: 40px;
padding: 0 10px;
background: #1e1e1e;
text-shadow: none;
box-shadow: none;
-webkit-box-shadow: none;
font-weight: 400;
margin-top: 15px;
}
#privacy {
font-size: 12px;
}
.invalid {
border-color: #ed0000;
background-color: #ffd8d8;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<!-- JQUERY CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!-- JAVASCRIPT -->
<script src="script.js"></script>
</head>
<body>
<noscript>
For full functionality of this site it is necessary to enable JavaScript.
Here are the <a href="http://www.enable-javascript.com/" target="_blank">
instructions how to enable JavaScript in your web browser</a>.
</noscript>
<div>
<form id="entry">
<label for="first_name">First name:</label>
<input id="first_name" type="text" name="first_name" />
<label for="last_name">Last name:</label>
<input id="last_name" type="text" name="last_name" />
<label>Country/Region</label>
<select id="country" name="country">
<option value="">Select Your Country/Region</option>
<option value="GB">United Kingdom</option>
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
</select>
<label for="email">Email:</label>
<input id="email" type="text" name="email" />
<label>Date of Birth</label>
<select id="birth_day" name="birth_day">
<option value="">DD</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>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select id="birth_month" name="birth_month">
<option value="">MM</option>
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
<select id="birth_year" name="birth_year">
<option value="">YYYY</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
</select>
<div id="privacy">
<input id="privacy_check" type="checkbox" name="privacy_check" />
<label for="privacy_check">I have read and understood the Terms and Conditions.</label>
</div>
<input type="submit" name="ch_access" value="Submit" />
</form>
</div>
</body>
</html>
You could create a function that performs the if/else statements:
function setInvalidClass(invalidCondition, jQueryObject) {
if(invalidCondition) {
jQueryObject.addClass('invalid');
}
else {
jQueryObject.removeClass('invalid');
}
}
then replace all the if/else statements with a call to the setInvalidClass:
setInvalidClass(!app.validation.email(userEmail), userEmail);
setInvalidClass(!app.validation.empty(userName), userName);
...
You could give a class to the inputs for the type of validation and then just loop through them:
$("#entry").submit(function(event) {
var emptyInputs = $(".empty"), // for empty validation give inputs class of empty
emailInputs = $(".email"), // for email validation give inputs class of email
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
emptyInputs.each(function() {
var input = $(this);
if (!app.validation.empty(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
emailInputs.each(function() {
var input = $(this);
if (!app.validation.email(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});
or alternatively give all inputs that need validating the same class with a data attribute of what type of validation it is:
$("#entry").submit(function(event) {
var inputs = $(".validation"),
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
inputs.each(function() {
var input = $(this),
validationType = input.data('validation-type'),
inputValid;
switch (validationType) {
case 'email':
inputValid = app.validation.email(input);
break;
case 'empty':
inputValid = app.validation.empty(input);
break;
}
if (!inputValid) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) { // this could be added to the loop - just wasn't sure what terms-con element is
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});

Change color of option in select element

I am trying to change the color of the selected option in a select element while it's in the drop down and while it's displayed in main window. So far I have been able to change the color of all the options.
<select id="drop-down" onchange="colorChange(event);">
<option value="">--</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
This is the function I'm using.
var one = "one";
var two = "two";
var three = "three";
var four = "four";
function colorChange(event){
if(event.target.value == one){
event.target.style.color = "#67D986";
} else if (event.target.value == two || three || four){
event.target.style.color = "#f00";
} else{
alert("There has been an error!!!");
}
};
There is problem in your else if in OR condition, to add conditions in OR use following
} else if (event.target.value == two || event.target.value == three || event.target.value == four) {
var colors = {
one: '#67D986',
two: '#f00',
three: '#f00',
four: '#f00'
};
$('#drop-down').on('change', function(e) {
var value = $('option:selected').val();
$('option').css('color', '#000');
if (!value) {
alert("There has been an error!!!");
} else {
$('option:selected').css('color', colors[value]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="drop-down">
<option value="">--</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
Do it in jquery way if you like:
$(document).ready(function(){
$("#drop-down").on("change",function(){
var selectedVal = $(this).val();
switch(selectedVal)
{
case "one": $(this).css("color","red")
break;
case "two": $(this).css("color","blue");
break;
}
});
});
Html
<select id="drop-down" >
<option value="">--</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
hi i think you can achieve this even by css only here i is that check out
select{
margin:40px;
color:#fff;
text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
select option {
margin:40px;
background: rgba(0,0,0,0.3);
color:#fff;
text-shadow:0 1px 0 rgba(0,0,0,0.4);
}
select option[val="one"]{
background: #67D986;
}
select option[val="two"],select option[val="three"],select option[val="four"]{
background: #f00;
}
<select id="drop-down">
<option val="">-----------------</option>
<option val="one">One</option>
<option val="two">Two</option>
<option val="three">Three</option>
<option val="four">Four</option>
</select>
Check By only CSS

Categories