I have a div that contains many classes. If the the div is clicked on and one of it's classes matches the value any option in the select box, i want that option to be selected.
<div class="abc cdf fff r10 yyy">
<select id="whatever">
<option value="r10">test10</option>
<option value="r20">test20</option>
<option value="r30">test30</option>
</select>
How do i achieve this with JavaScript or jQuery
I tried the following but can't get it to work.
var roundclasses = $(this).attr('class').split(/\s/); //This outputs the array of classes sucessfully
for (var i in roundclasses){
$('#whatever').val(roundclasses[i]);
}
Here is the JSBin snippet.
HTML:
<div id="clickDiv" class="abc cdf fff r30 yyy">
<p>CLICK</p>
</div>
<select id="whatever">
<option value="r10">test10</option>
<option value="r20">test20</option>
<option value="r30">test30</option>
</select>
JS (using jQuery):
var div = $("#clickDiv");
var sel = $("#whatever");
var options = $("#whatever option");
div.click(function() {
options.each(function(index, e) {
if (div.hasClass(e.value)) {
sel.val(e.value);
}
});
});
EDIT:
Created a JSBin with shorter solution - HERE
var div = $("#clickDiv");
var options = $("#whatever option");
div.click(function() {
options.attr('selected', function() {
return div.hasClass(this.value);
});
});
Here is the jsFiddle.
HTML:
<div id="clickme" class="abc cdf fff r10 yyy">Click Me</div>
<br>
<br>
<select multiple="true" id="dd">
<option value="r1">test1 (r1)</option>
<option value="r2">test2 (r2)</option>
<option value="r2">test3 (cdf)</option>
<option value="yyy">test4 (yyy)</option>
<option value="r10">test9 (r10)</option>
<option value="r10">test10 (r10)</option>
</select>
CSS:
#clickme {
background: #FF0000;
color: #FFF;
font: 14px Arial, sans-serif;
height: 100px;
line-height: 100px;
text-align: center;
width: 100px;
}
JS:
var $dd = $("#dd"),
$dd_opts = $dd.find('option');
$("#clickme").click(function() {
var classes = $(this).attr('class').split(' '),
class_len = classes.length;
$dd.val('');
for (x = 0, class_len = classes.length; x < class_len; x++) {
var cls = classes[x],
$opts = $dd_opts.filter('[value="'+ cls +'"]');
$opts.attr('selected', 'selected');
}
});
Related
I have 3 text in combobox (primary,danger,warning) when i clicked the one of that, text will be displayed based on the combobox selected with the background color, the example, i select danger text in combobox that will displayed text danger with the red background, how i to make it in php, javascript?
https://prnt.sc/qfqx2v
https://prnt.sc/qfqx86
i have example just click the link on top
In your css you can do something like this :
(if you use radio buttons):
.input[type="radio"]:checked {
background-color: blue;
}
(if you use dropdown):
option:checked {
background: red;
}
As you said combobox you can use wijmo library and code (full-screen to test snippets) and JSfiddle
onload = function() {
// create some random data
var names = 'primary,warning,danger'.split(','),
data = [];
for (var i = 0; i < names.length; i++) {
data.push({
name: names[i]
});
}
var theComboString = new wijmo.input.ComboBox('#theComboString', {
selectedIndexChanged: function(s, e) {
setText('theComboStringCurrent', s.text);
},
itemsSource: names
});
// show text in an element on the page
function setText(id, value) {
document.getElementById(id).textContent = value;
if(value=="primary")
{
$("#theComboString").css("background-color","green");
}
if(value=="danger")
{
$("#theComboString").css("background-color","red");
}
if(value=="warning")
{
$("#theComboString").css("background-color","orange");
}
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.grapecity.com/wijmo/5.latest/styles/wijmo.min.css" rel="stylesheet"/>
<script src="https://cdn.grapecity.com/wijmo/5.latest/controls/wijmo.min.js"></script>
<script src="https://cdn.grapecity.com/wijmo/5.latest/controls/wijmo.input.min.js"></script>
<div class="container">
<h1>
ComboBox
</h1>
<label for="theComboString">Strings:</label>
<div id="theComboString"></div>
<p>
The current value is: <b id="theComboStringCurrent"></b>.
</p>
</div>
You could do it like this using plain javascript.
JSFiddle Demo
I put comments in the code for explanation.
// Select the dropdown color selector.
var colorSelect = document.querySelector("#colors");
// Add a function to run, each time a new option(color) is selected.'
colorSelect.addEventListener("change", changeColor);
// Run the function from the previous event listener.
// The function get the color with "this.value", where this is the selected value.
// This works since each option has a value in the markup, otherwise you had to get the text value.
// Then it sets the background color of the body to the selected color.
function changeColor() {
var selectedValue = this.value;
document.body.style.backgroundColor = selectedValue;
}
<select name="colors" id="colors">
<option value=""></option>
<option value="red">red</option>
<option value="blue">blue</option>
<option value="green">green</option>
</select>
Updated answer
Working demo
var box = document.querySelector(".box");
var colorSelect = document.querySelector("#colors");
colorSelect.addEventListener("change", changeColor);
function changeColor() {
var selectedColor = this.value;
var selectedType = colorSelect.options[colorSelect.selectedIndex].text;
box.style.backgroundColor = selectedColor;
box.innerHTML = selectedType;
}
.box {
height: 20px;
width: 200px;
}
<div class="box"></div>
<select name="colors" id="colors">
<option value=""></option>
<option value="red">Danger</option>
<option value="yellow">Warning</option>
<option value="green">Success</option>
</select>
I have select box with some values and using AJAX to send data to php and display those data inside <div> , Here is my code I don't know why this is not working.
When I used button to get value from It was working. I have tried multiple tutorials and red a lot of question regarding AJAX and select box.
I tried making funciton and inside select calling it with onchange
product.php
<div id="input-option232">
<div class="checkbox">
<div class="custom-select" style="width: 200px">
<form method="get" name="rate">
<select name="rate2" id="rate2">
<option value="0">Broj Rata:</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>
</select>
</form>
</div>
</div>
<div id="ratice"></div> // I WANT TO DISPLAY HERE
</div>
aj-select.js
$("#rate2").on('change', function() {
var level = $('#rate2').val();
if(level){
$.ajax ({
type: 'GET',
url: 'rate.php',
data: 'rate='+level,
success : function(data) {
$('#ratice').html(data);
}
});
}
});
rate.php
<?php
if(isset($_GET['rate'])){
echo $rate = $_GET['rate'];
}
?>
select.js
var x, i, j, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
selElmnt = x[i].getElementsByTagName("select")[0];
/*for each element, create a new DIV that will act as the selected item:*/
a = document.createElement("DIV");
a.setAttribute("class", "select-selected");
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
/*for each element, create a new DIV that will contain the option list:*/
b = document.createElement("DIV");
b.setAttribute("class", "select-items select-hide");
for (j = 0; j < selElmnt.length; j++) {
/*for each option in the original select element,
create a new DIV that will act as an option item:*/
c = document.createElement("DIV");
c.innerHTML = selElmnt.options[j].innerHTML;
c.addEventListener("click", function(e) {
/*when an item is clicked, update the original select box,
and the selected item:*/
var y, i, k, s, h;
s = this.parentNode.parentNode.getElementsByTagName("select")[0];
h = this.parentNode.previousSibling;
for (i = 0; i < s.length; i++) {
if (s.options[i].innerHTML === this.innerHTML) {
s.selectedIndex = i;
h.innerHTML = this.innerHTML;
y = this.parentNode.getElementsByClassName("same-as-selected");
for (k = 0; k < y.length; k++) {
y[k].removeAttribute("class");
}
this.setAttribute("class", "same-as-selected");
break;
}
}
h.click();
});
b.appendChild(c);
}
x[i].appendChild(b);
a.addEventListener("click", function(e) {
/*when the select box is clicked, close any other select boxes,
and open/close the current select box:*/
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle("select-hide");
this.classList.toggle("select-arrow-active");
});
}
function closeAllSelect(elmnt) {
/*a function that will close all select boxes in the document,
except the current select box:*/
var x, y, i, arrNo = [];
x = document.getElementsByClassName("select-items");
y = document.getElementsByClassName("select-selected");
for (i = 0; i < y.length; i++) {
if (elmnt === y[i]) {
arrNo.push(i);
} else {
y[i].classList.remove("select-arrow-active");
}
}
for (i = 0; i < x.length; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add("select-hide");
}
}
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);
CSS
<style type="text/css">
body{font-family:'Roboto', sans-serif}
.custom-select {
position: relative;
font-family: Arial;
}
.custom-select select {
display: none; /*hide original SELECT element:*/
}
.select-selected {
background-color: #f4a137;
}
/*style the arrow inside the select element:*/
.select-selected:after {
position: absolute;
content: "";
top: 14px;
right: 10px;
width: 0;
height: 0;
border: 6px solid transparent;
border-color: #fff transparent transparent transparent;
}
/*point the arrow upwards when the select box is open (active):*/
.select-selected.select-arrow-active:after {
border-color: transparent transparent #fff transparent;
top: 7px;
}
/*style the items (options), including the selected item:*/
.select-items div,.select-selected {
color: #ffffff;
padding: 8px 16px;
border: 1px solid transparent;
border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
cursor: pointer;
user-select: none;
}
/*style items (options):*/
.select-items {
position: absolute;
background-color: #f4a137;
top: 100%;
left: 0;
right: 0;
z-index: 99;
}
/*hide the items when the select box is closed:*/
.select-hide {
display: none;
}
.select-items div:hover, .same-as-selected {
background-color: rgba(0, 0, 0, 0.1);
}
</style>
So... You use a plugin to obtain a "fancier" select...
That plugin creates some new DOM elements... So the user do not really interact with the select of your original markup. It is only used to create the new ones... Then hidden.
Here is what's created as siblings of your <form>:
<div class="custom-select" style="width: 200px">
<form method="get" name="rate">
<select name="rate2" id="rate2">
<option value="0">Broj Rata:</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>
</select>
</form>
<div class="select-selected">
Broj Rata:
</div>
<div class="select-items select-hide">
<div>Broj Rata:</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
</div>
</div>
So we now need to use another selector to capture the user interaction.
Replace:
$("#rate2").on('change', function() {
with
$("[name='rate']+.select-selected+.select-items").on("click",function(){
The + sign in the selector is an "adjacent sibling selector". It targets the last one IF it immediately follows the previous (as a sibling in DOM).
And that makes the trick here very well.
CodePen
Change the value of the data property to object data: {'rate':level}
$("#rate2").on('change', function() {
var level = $('#rate2').val();
if(level){
$.ajax ({
type: 'GET',
url: 'rate.php',
data: {'rate':level},
success : function(data) {
$('#ratice').html(data);
}
});
}
});
<?php
if(isset($_GET['rate'])){
$rate = $_GET['rate'];
echo $rate;
}
?>
Try next modifications, and check the developer console for messages in order to get some debugging.
aj-select.js
$("#rate2").on('change', function()
{
var level = $('#rate2').val();
console.log("Selected level is : " + level);
if (level < 0) return;
$.ajax ({
type: 'GET',
url: 'rate.php',
dataType: 'json',
data: {'rate':level},
success: function(data)
{
console.log("SUCCESS - data is: " + data);
$('#ratice').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("ERROR: " + textStatus + " " + errorThrown);
}
});
});
rate.php
<?php
if (isset($_GET['rate']))
{
echo json_encode($_GET['rate']);
}
?>
The following snippet is working, so the problem must be either on the ajax call or the php script itself. Check the Network pane on the DevTools to see what's being sent to the server.
$("#rate2").on('change', function() {
var level = $('#rate2').val();
if (level) {
$('#ratice').html(level);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input-option232">
<div class="checkbox">
<div class="custom-select" style="width: 200px">
<form method="get" name="rate">
<select name="rate2" id="rate2">
<option value="0">Broj Rata:</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
</div>
<div id="ratice"></div>
</div>
I have two multi selects viz. mySelectNumberTest1 and mySelectNumberTest2. What I want to do is be able to select items in the first dropdown and when I click on a checkbox/button or any control that will trigger an event, it should take the options from mySelectNumberTest1 and populates it into mySelectNumberTest2.
I have followed this link: Get selected value in dropdown list using JavaScript? its a partial solution to my problem. The only thing that's missing is that if you select more than one item in mySelectNumberTest1 it will only take the first item and populate it into mySelectNumberTest2.
The below code only works when I am populating items from a select into a normal input textbox.
<select id="mySelectNumberTest1" name="mySelectNumberTest" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="checkbox" id="tickHereToMove" />
<input id="mySelectNumberTest2" name="mySelectNumberTest2" type="text" onchange="copyTextValueTest(this);" />
function copyTextValueTest(bf) {
var e = document.getElementById("mySelectNumberTest1");
var strUser = e.options[e.selectedIndex].text;
document.getElementById("mySelectNumberTest2").value = strUser;
alert(strUser);
}
There's also a few problems with this approach as it concatenates the text. I tried the .split() function and that still didn't give me the result I wanted. I want the selected items in each line on mySelectNumberTest2.
This library http://quasipartikel.at/multiselect/ does EXACTLY what I want to do. I am working in an Angular JS project and when I try include the jquery scripts in my index.html page, it causes anomalous behaviour and messes up the styling of the page as well.
So if I select 1 and 3 in mySelectNumberTest1, it should populate it in mySelectNumberTest2 in two different lines and not 12.
If this can be achieved in a drag and drop implementation I would also be happy.
Simply do this:
function addOptions( fromId, toId ) {
var fromEl = document.getElementById( fromId ),
toEl = document.getElementById( toId );
if ( fromEl.selectedIndex >= 0 ) {
var index = toEl.options.length;
for ( var i = 0; i < fromEl.options.length; i++ ) {
if ( fromEl.options[ i ].selected ) {
toEl.options[ index ] = fromEl.options[ i ];
i--;
index++
}
}
}
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
grid-template-columns: 70px 40px 70px;
grid-gap: 10px
}
select {
width: 70px
}
li.relative {
position: relative
}
#add {
position: absolute;
width: 40px;
font-size: 18px;
top: 0
}
#remove {
position: absolute;
width: 40px;
font-size: 18px;
bottom: 0
}
<ul>
<li>
<select id="select1" name="select1" multiple>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
</select>
</li>
<li class="relative">
<input type="button" id="add" value="⇾" onclick="addOptions( 'select1', 'select2' )" />
<input type="button" id="remove" value="⇽" onclick="addOptions( 'select2', 'select1' )" />
</li>
<li>
<select id="select2" name="select2" multiple></select>
</li>
</ul>
I want to check if there is an option in select then show the div if not then hide. I am not checking selected option I am checking all options.
if (jQuery(".sd select option").text() == 'S') {
console.log('hello');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="input-box sd">
<select name="options[1261]" id="select_1261" class=" required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
<option value="">-- Please Select --</option>
<option value="6888" price="0">S </option>
<option value="6889" price="0">M </option>
</select>
</div>
if there is an option in select
You can use .filter() to iterate over the options and check them length of the matched items, similar to this.
var hasOptionS = $('select option').filter(function(){return this.text.trim().toUpperCase() === 'S'}).length > 0;
var hasOptionP = $('select option').filter(function(){return this.text.trim().toUpperCase() === 'P'}).length > 0;
console.log('has Option S:', hasOptionS);
console.log('has Option P:', hasOptionP);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="input-box sd">
<select name="options[1261]" id="select_1261" class=" required-entry product-custom-option" title="">
<option value="">-- Please Select --</option>
<option value="6888" price="0">S </option>
<option value="6889" price="0">M </option>
</select>
</div>
then show the div if not then hide
Ones you have the result you can use it in your conditional check, similar to this:
if(hasOption){
$(yourDiv).show();
} else {
$(yourDiv).hide();
}
var theSelect = document.getElementById("select_1261");
var stop = false;
for (var i = 0; i < theSelect.options.length & stop != true; i++) {
switch (theSelect.options[i].innerHTML) {
case "S ":
case "M ":
document.getElementById("cooldiv").style.display = "none";//hide the div
stop = true;
break;
default:
break;
}
}
$('.dropdown').each(function() {
var _length = $(this).children('option').length - 1;
//console.log(_length);
if (_length < 1) {
$(this).hide();
}
});
.dropdown-box {
display: inline-block;
background-color: #F4F4F4;
margin: 10px;
padding: 20px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown-box">
<p>Has values:</p>
<div class="input-box">
<select name="options[1261]" id="select_1261" class="dropdown">
<option value="">-- Please Select --</option>
<option value="6888" price="0">S </option>
<option value="6889" price="0">M </option>
</select>
</div>
</div>
<div class="dropdown-box">
<p>Has no values:</p>
<div class="input-box">
<select name="options[1261]" id="select_1261" class="dropdown">
<option value="">-- Please Select --</option>
</select>
</div>
</div>
I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option> </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
your help will be highly appreciated.
Thanks
You can try adding <br/> element after every selected option. I have used <label> element but you can add link or any other element you want
$(document).ready( function ()
{
$('#select-custom-19').change(function(){
$('#yourfruit').empty();
var values = $(this).val();
for(var i=0; i < values.length ; i++)
{
$('#yourfruit').append('<lable>'+values[i]+'</label><br/>');
}
});
});
JSFiddle Demo
You can iterate throug items and display them, append an anchor (<a />) and use <br /> for a new line.
Make sure to add .empty() to clean the fruits from list before .append() other items to $('#yourfruit'), like in example below.
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit]+" - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit] + " - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
});
});
.tab-btn {
color: red;
}
.tab-btn:hover {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; ">
<span id="yourfruit"> </span>
</div>
try below
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903; color:#000000; margin: 10px; ">
<ul id="yourfruit">
</ul>
</div>
<script type="text/javascript">
$(document).ready( function ()
{
$('#select-custom-19').change(function()
{
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').append('<li>'+$(this).val()+'</li>');
}
);
});
</script>
You may add HTML tags as per your requirements, like <a> or </br>
$(document).ready(function () {
$('#select-custom-19').change(function () {
$('#yourfruit').text("");
if($(this).val() != null)
{
$(this).val().forEach(function (value, index) {
$('#yourfruit').append("<a href='#'>" + value + "</a></br>");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>