CSS Checkbox style to toggle a value - javascript

I am currently writing a program which toggles a value based on the status of a checkbox. With a normal checkbox everything works fine.
HTML:
<td><script> checkbox('px_THPressure_Enable')</script></td>
<td><script> checkbox('px_THPressure_Activate')</script></td>
Javascript checkbox function:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<input type='checkbox' class='fetch' onClick=\""+onClicked+"\" id='" + register + "'>";
document.write(output);
}
Now I am trying to style the checkbox with CSS as described here http://www.paulund.co.uk/style-checkboxes-with-css "Checkbox Four"
So now my checkbox function changed to:
function checkbox(register)
{
var onClicked = "setDataJQuery('"+register+"',this.checked?'1':'0')";
var output = "<div class='checkboxFour'><input type='checkbox' class='fetch' value='1' onClick=\""+onClicked+"\" id='" + register + "' name=''></input><label for='checkboxFourInput'></label></div>";
document.write(output);
}
CSS:
input[type=checkbox] {
visibility: hidden;
}
/**
* Checkbox Four
*/
.checkboxFour {
width: 40px;
height: 40px;
background: #ddd;
margin: 20px 90px;
border-radius: 100%;
position: relative;
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checkbox button
*/
.checkboxFour label {
display: block;
width: 30px;
height: 30px;
border-radius: 100px;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
-o-transition: all .5s ease;
-ms-transition: all .5s ease;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 5px;
left: 5px;
z-index: 1;
background: #333;
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);
}
/**
* Create the checked state
*/
.checkboxFour input[type=checkbox]:checked + label {
background: #26ca28;
}
Now I am able to see the correct status of the checkbox with the new style but when I click the checkbox the value does not change. I know that the issue is in the id field. The checkbox style requires the id="checkboxFourInput" and my program requires the id to equal the register value which is being toggled. ie THPressure_Enable
I know that having multiple ids on an html element is not allowed, so is there any way that I can toggle this register value with the styled checkbox.
Thank you in advance.
EDIT:
It is a function that will change the register value depending on the correct authorization. I have the function defined as follows:
function setDataJQuery(register,value)
{
statusElem = document.getElementById('status');
if (statusElem)
statusElem.innerHTML=" ";
//alert("logged in as " + "<?php echo \"{$_SERVER['PHP_AUTH_USER']}\"; ?>");
if (((user_name == 'slipsmart' || user_name== 'slipsmart_super') && (operator_set_ok.indexOf(register.substring(3)) != -1)) ||
(user_name == 'slipsmart_super' && (supervisor_set_ok.indexOf(register.substring(3)) != -1)) ||
user_name == 'slipsmart_setup')
{
$.ajax({
url: 'set.php?' + register + '=' + value,
type: 'post',
success:function(data){
var val_pairs = data.split("&");
document.getElementById('Error').innerHTML=" ";
for (i in val_pairs)
{
var pair = val_pairs[i].split("=");
var myElem = document.getElementById(pair[0]);
if (myElem)
myElem.innerHTML= pair[1];
}
}
});
}
else
alert("Not authorized!");
}

Related

Hiding an element in internet explorer leaves artifacts on the screen (IE 10-11)

We use custom selectbox elements for our page (for reasons), but in one specific place and only with IE (in my case version 10 and 11), there is a problem.
When you open the box and close it, sometimes the browser leaves visual artifacts of that element. If there is a button below the element (in the opened state), then those artifacts are still on top of that button UNTIL you hover over the button, then those artifacts disappear at that place.
I think everyone experienced this behaviour at some point in his life with windows or something else. Sorry if my description isn't perfect.
Here are some screenshots (The red boxes are censored text, sorry):
Open state:
Closed state with artifacts:
Hope my description is accurate, I desperately need a fix for this.
I can't reproduce it on my system, but our QA guy can reproduce it consistently. It also changes depending on the size of the browser. On some sizes it doesn't seem to happen at all. It must be some weird rendering glitch of IE.
I don't think it has anything to do with our custom selectbox element, because it happens only in this specific place and in our old design we experienced it in a different place with a completely different element. At that time I thought it's because the DOM is too complicated for IE, but this page has almost no elements.
EDIT: I Just found out that if I minimize the window and maximize it again, the artifacts disappear, which should confirm that this is a rendering glitch, right?
EDIT 2: Here is the code and css of our custom selectbox
HTML:
<div class="input_selectbox">
<label>Title</label>
<div class="input_selectbox__head" data-placeholder="">
<label>
<input type="hidden" name="id" value="5-10909">
Dummy 1
</label>
</div>
<div class="input_selectbox__body">
<label data-value="" class="">
No Option
</label>
<label id="5-10909" data-value="5-10909" class="input_selectbox__option--selected" data-default="true">
Dummy 1
</label>
<label id="5-12568" data-value="5-12568" class="">
Dummy 2
</label>
<label id="5-20001" data-value="5-20001" class="">
Dummy 3
</label>
<label id="5-20002" data-value="5-20002" class="">
Dummy 4
</label>
</div>
</div>
LESS:
.input_combobox, .input_selectbox {
display: block;
font-family: RobotoCondensed-Regular;
font-size: 14px;
width: 100%;
overflow: hidden;
&:focus {
outline: none;
}
label {
cursor: pointer;
}
}
.input_selectbox {
font-family: Roboto-Regular;
}
.input_selectbox__head {
border: 1px solid #colorBorderGrey;
transition: background-color 0.2s, border 0.3s;
overflow-x: hidden;
text-overflow: ellipsis;
display: flex;
background-color: #colorLightestGrey;
padding: 10px;
justify-content: space-between;
&:hover {
cursor: pointer;
border-color: #colorDarkGrey;
&:after {
color: #colorBlue;
}
}
label {
display: flex;
user-select: none;
pointer-events: none;
i {
margin-right: 10px;
}
}
&:after {
content: "\f078";
font-style: normal;
font-variant: normal;
text-rendering: auto;
font-family: "Font Awesome 5 Pro";
font-weight: 900;
pointer-events: none;
transition: color 0.3s, opacity 0.3s, background-color 0.2s;
display: block;
padding-left: 10px;
font-size: 16px;
}
}
.input_combobox--active, .input_selectbox--active {
.input_combobox__head, .input_selectbox__head {
background-color: #colorLightGrey;
&:hover {
border: 1px solid #colorBorderGrey;
&:after {
color: #colorDarkGrey;
}
}
&:after {
background-color: #colorLightGrey;
}
span {
background-color: #colorGreyHover;
}
}
}
.input_combobox__body, .input_selectbox__body {
display: none;
position: fixed;
box-shadow: rgba(0,0,0, 0.05) 0px 2px 5px 0px;
background-color: #colorWhite;
border: 1px solid #colorBorderGrey;
border-top: none;
max-height: 400px;
overflow-y: auto;
width: 100%;
z-index: 499;
label {
font-family: RobotoCondensed-Regular;
font-size: 16px;
display: block;
padding: 10px 20px;
transition: background-color 0.5s, color 0.3s;
border-bottom: 1px solid #colorBorderGrey;
&:hover {
background-color: #colorLightGrey;
}
&:last-child {
border-bottom: none;
}
i {
margin-right: 10px;
}
input[type=checkbox] {
display: none;
}
}
}
.input_combobox__body--top, .input_selectbox__body--top {
box-shadow: rgba(0, 0, 0, 0.1) 0px -2px 5px 0px;
}
.input_combobox__option--inactive, .input_selectbox__option--inactive {
opacity: 0.3;
}
Javascript:
function selectbox()
{
// click
$(document).on("click", ".input_selectbox__head", function ()
{
$(this).trigger("selectbox:toggle");
});
// toggle
$(document).on("selectbox:toggle", ".input_selectbox__head", function ()
{
if ($(this).parent().hasClass("input_selectbox--active"))
{
$(this).trigger("selectbox:close");
}
else
{
$(this).trigger("selectbox:open");
}
});
// open
$(document).on("selectbox:open", ".input_selectbox__head", function ()
{
var selectbox = $(this).closest(".input_selectbox");
if (!selectbox.hasClass("readonly") && !selectbox.hasClass("input--disabled"))
{
$(".input_selectbox--active .input_selectbox__head").trigger("selectbox:close");
// Positionierung
var header = selectbox.find(".input_selectbox__head");
var headerHeight = header.outerHeight();
var selectboxBody = selectbox.find(".input_selectbox__body");
var headerPositionX = header.offset().left;
var headerPositionY = header.offset().top - $(window).scrollTop();
var bodyPositionY = headerPositionY + headerHeight;
selectboxBody.removeClass("input_selectbox__body--top");
selectboxBody.css({
"top": bodyPositionY,
"left": headerPositionX,
"width": selectbox.width(),
"bottom": ""
});
selectbox.addClass("input_selectbox--active");
selectboxBody.show();
// check if offscreen
var isOut = isOutOfViewport(selectboxBody.get(0));
if (isOut.bottom)
{
selectboxBody.addClass("input_selectbox__body--top");
selectboxBody.css({
top: "",
bottom: ($(window).innerHeight() - headerPositionY - 1)
});
}
// close combobox on parent scroll
var scrollParent = getScrollParent(header[0]);
$(scrollParent).one("scroll", function ()
{
header.trigger("selectbox:close");
});
$(document).one("scroll", function ()
{
header.trigger("selectbox:close");
});
$(window).one("resize", function ()
{
header.trigger("selectbox:close");
});
}
});
// close
$(document).on("selectbox:close", ".input_selectbox__head", function ()
{
var selectbox = $(this).closest(".input_selectbox");
selectbox.removeClass("input_selectbox--active");
var selectboxBody = selectbox.find(".input_selectbox__body");
selectboxBody.hide();
});
// change option
$(document).on("click", ".input_selectbox__body > label", function ()
{
var label = $(this);
var value = label.attr("data-value");
var headerLabel = $(this).closest(".input_selectbox__body").siblings(".input_selectbox__head").children("label");
var name = headerLabel.find("input[type=hidden]").attr("name");
label.addClass("input_selectbox__option--selected").siblings().removeClass("input_selectbox__option--selected");
headerLabel.html(label.html());
headerLabel.append('<input type="hidden" name="' + name + '" value="' + value + '" />');
headerLabel.closest(".input_selectbox__head").trigger("selectbox:close");
$(this).closest(".input_selectbox").trigger("selectbox:change").trigger("change");
});
// close selectbox on outside click
$(document).ready(function ()
{
$(document).on("click touchstart", function (event)
{
if ($(event.target).closest('.input_selectbox--active').length == 0)
{
$(".input_selectbox--active .input_selectbox__head").trigger("selectbox:close");
}
});
});
// form reset
$(document).on("reset", "form", function ()
{
var selectboxes = $(this).find(".input_selectbox");
selectboxes.each(function ()
{
$(this).find(".input_selectbox__body").find("label[data-default=true]").click();
});
});
}

XMLHttpRequest is not working in the WordPress

I'm trying to send a variable to the server, using XMLHttpRequest.
I tested it on local on a non-Wordpress file and it works. But on production, on my Wordpress file, the onreadystatechange AJAX status doesn't get to 200.
Is there anything I need to be aware when XMLHttpRequesting in Wordpress?
I have the following code for sending data to the server using XMLHTTP Request but it's not working I don't know why? I'm getting the following error:
VM704:1 POST http://localhost/amt/wp-admin/admin-ajax.php 400 (Bad Request)
here is my WordPress code:
add_action('wp_ajax_csv_file', 'csv_file');
add_action('wp_ajax_nopriv_csv_file', 'csv_file');
function csv_file()
{
if($_POST['rtype'] == 'enr_data'){
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
for ($i = 0; $i < 10; $i++) {
//Hard work!!
sleep(1);
$p = ($i + 1) * 10; //Progress
$response = array('message' => $p . '% complete. server time: ' . date("h:i:s", time()),
'progress' => $p);
echo json_encode($response);
}
sleep(1);
$response = array('message' => 'Complete',
'progress' => 100);
echo json_encode($response);
die();
}
}
function ajax_stream() {
if (!window.XMLHttpRequest) {
alert("Your browser does not support the native XMLHttpRequest object.");
return;
}
try {
var xhr = new XMLHttpRequest();
xhr.previous_text = '';
xhr.responseType = "text";
xhr.onerror = function() {
alert("[XHR] Fatal Error.");
};
xhr.onreadystatechange = function() {
try {
if (xhr.readyState == 4) {
alert('[XHR] Done')
} else if (xhr.readyState > 2) {
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse(new_response);
document.getElementById("divProgress").innerHTML += result.message + '<br />';
document.getElementById('progressor').style.width = result.progress + "%";
xhr.previous_text = xhr.responseText;
}
} catch (e) {
alert("[XHR STATECHANGE] Exception: " + e);
}
};
var data = "action=csv_file&rtype=enr_data";
xhr.open("POST", ajaxurl, true);
xhr.send(data);
console.log(xhr);
} catch (e) {
alert("[XHR REQUEST] Exception: " + e);
}
}
#divProgress {
border: 2px solid #ddd;
padding: 10px;
width: 300px;
height: 265px;
margin-top: 10px;
overflow: auto;
background: #f5f5f5;
}
#progress_wrapper {
border: 2px solid #ddd;
width: 321px;
height: 20px;
overflow: auto;
background: #f5f5f5;
margin-top: 10px;
}
#progressor {
background: #07c;
width: 0%;
height: 100%;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}
.demo_container {
width: 680px;
margin: 0 auto;
padding: 30px;
background: #FFF;
margin-top: 50px;
}
.my-btn,
.my-btn2 {
width: 297px;
margin-top: 22px;
float: none;
display: block;
}
h1 {
font-size: 22px;
margin-bottom: 20px;
}
.float_left {
float: left;
}
.float_right {
float: right;
}
.demo_container::after {
content: "";
clear: both;
display: block;
}
.ghost-btn.active {
border: 2px solid #D23725;
color: #D23725;
}
.ghost-btn {
display: inline-block;
text-decoration: none;
border: 2px solid #3b8dbd;
line-height: 15px;
color: #3b8dbd;
-webkit-border-radius: 3px;
-webkit-background-clip: padding-box;
-moz-border-radius: 3px;
-moz-background-clip: padding;
border-radius: 3px;
background-clip: padding-box;
font-size: 15px;
padding: .6em 1.5em;
-webkit-transition: all 0.2s ease-out;
-moz-transition: all 0.2s ease-out;
-o-transition: all 0.2s ease-out;
transition: all 0.2s ease-out;
background: #ffffff;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
cursor: pointer;
zoom: 1;
-webkit-backface-visibility: hidden;
position: relative;
margin-right: 10px;
}
.ghost-btn:hover {
-webkit-transition: 0.2s ease;
-moz-transition: 0.2s ease;
-o-transition: 0.2s ease;
transition: 0.2s ease;
background-color: #3b8dbd;
color: #ffffff;
}
.ghost-btn:focus {
outline: none;
}
.ghost-btn.active {
border: 2px solid #D23725;
color: #D23725;
}
.ghost-btn.active:hover {
border: 2px solid #D23725;
background: #FFF;
}
.method_wrappers {
margin-bottom: 20px;
}
<div class="demo_container">
<div class='method_wrappers'>
<a class='ghost-btn active' href='#'>XHR Method</a>
<a class='ghost-btn' href='../example2/index.html'>Iframe Method</a>
</div>
<h1>AJAX progress bar for PHP script without polling (XHR method)</h1>
<div class='float_left'>
<h3>Progress Bar</h3>
<div id='progress_wrapper'>
<div id="progressor"></div>
</div>
<a onclick="ajax_stream();" class='my-btn'>Start Ajax Streaming</a>
</div>
<div class='float_right'>
<h3>Log</h3>
<div id="divProgress"></div>
</div>
</div>
When using an XHR instead of a jQuery/AJAX request, I found it's actually easier and more reliable to append the action to the ajaxurl.
var xhr = new XMLHttpRequest();
var url = ajaxurl + '?action=csv_file';
xhr.open( 'POST', url, true );
The method of passing data to the request varies a bit, but 95% of the time I use a simple object to query string function:
// Convert an Object into a Query String
function objectToQueryString(obj){
return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
}
Which in practice will turn a simple data object
var data = {
'post_id': ajax_object.post_id,
'rtype': 'enr_data',
'field': element.getAttribute('data-field'),
};
into a simple query string:
post_id=1234&rtype=enr_data&field=bar
This lets me pass the data off as a string posted to the target function:
var dataString = objectToQueryString( data );
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(dataString);
For larger or more complex tasks you can actually effectively wrap the whole thing in a Promise as well, which I'll do if for instance I need to upload a handful of files and pass those along one by one for resizing.
The right solution would be to use "encodeURIComponent". Which correctly transcodes all strings and characters. The function will be:
function encodeURI(obj) {
var result = '';
var splitter = '';
if (typeof obj === 'object') {
Object.keys(obj).forEach(function (key) {
result += splitter + key + '=' + encodeURIComponent(obj[key]);
splitter = '&';
});
}
return result;
},
End then use it in your request:
var data = {
action: 'your action',
data: JSON.stringify(data)
};
let request = new XMLHttpRequest();
request.open('POST', '/wp-admin/admin-ajax.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(encodeURI(data));

select elements in sequence (by group class name)

how do I select elements created dinamicamentes by groups? I want to select msgpvtstyleme and work on them. Then select msgpvtstyle again and work on them ... Goal is to get grouped elements and insert them classes .....
I want to simulate chat balloons
result final! Thank you all!
Here is a basic jQuery script which checks each element and detecting the following:
Check current class
If previous sibling has a different class then it will get first
If next sibling is of the same class, it will be middle
If next sibling is of another class, it will be marked as last
If previous and next siblings are of other classes, it will be first middle last
// define your container here
var container = $('.container'),
currentClass = container.children(":first").attr("class");
// run through each child
container.children('li').each(function() {
currentClass = $(this).attr("class");
if ( $(this).prev().attr("class") !== currentClass ) {
$(this).attr("data-order","first"); }
if ( $(this).next().attr("class") === currentClass && $(this).prev().attr("class") === currentClass ) {
$(this).attr("data-order","middle"); }
if ( $(this).next().attr("class") !== currentClass ) {
$(this).attr("data-order","last"); }
if ( $(this).next().attr("class") !== currentClass && $(this).prev().attr("class") !== currentClass ) {
$(this).attr("data-order","first middle last"); }
// debugging only
$(this).text( $(this).attr("class") + ': ' + $(this).attr('data-order') );
});
li[data-order~="first"] {font-weight: bold;}
li[data-order~="last"] {border-bottom:1px solid;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li class="class1"></li>
<li class="class1"></li>
<li class="class1"></li>
<li class="class2"></li>
<li class="class2"></li>
<li class="class1"></li>
</ul>
jsFiddle: https://jsfiddle.net/azizn/40trqhn4/
Note: I used data-order attribute instead class as altering the class name will break the checking function (since it all revolves around class name). You can access the elements through the CSS attribute selectors [data-order="first"] for example.
Here is a simple way:
function style_latest_messages() {
var classes = '.msgpvtstyle, .msgpvtstyleme';
$(classes).filter('.first,.middle,.last')
.last().removeClass('first middle last')
.add($(classes).not('.first,.middle,.last')).each(function() {
styleMessage(this);
});
function styleMessage(el) {
var prev = $(el).prevAll(classes).eq(0),
next = $(el).nextAll(classes).eq(0),
is_first = is_me(prev) != is_me(el) || !prev.length,
is_last = is_me(next) != is_me(el) || !next.length;
if(is_first) $(el).addClass('first');
if(is_last) $(el).addClass('last');
if(is_first == is_last) $(el).addClass('middle');
}
}
function is_me(el) { return $(el).hasClass('msgpvtstyleme'); }
Note that $(this).prevAll(classes).eq(0) and $(this).nextAll(classes).eq(0) will allow you to ignore any extra element, such as time. Try the demo to see what I mean.
Demo
style_latest_messages();
function style_latest_messages() {
var classes = '.msgpvtstyle, .msgpvtstyleme';
$(classes).filter('.first,.middle,.last')
.last().removeClass('first middle last')
.add($(classes).not('.first,.middle,.last')).each(function() {
styleMessage(this);
});
function styleMessage(el) {
var prev = $(el).prevAll(classes).eq(0),
next = $(el).nextAll(classes).eq(0),
is_first = is_me(prev) != is_me(el) || !prev.length,
is_last = is_me(next) != is_me(el) || !next.length;
if(is_first) $(el).addClass('first');
if(is_last) $(el).addClass('last');
if(is_first == is_last) $(el).addClass('middle');
}
}
function is_me(el) { return $(el).hasClass('msgpvtstyleme'); }
// Just for testing
var msgs=['<li class="time">17:52</li><li class="msgpvtstyleme">Don\'t forget to unload the dishwasher</li>', '<li class="msgpvtstyleme">Did you finish your homework?</li>', '<li class="msgpvtstyleme">Your grandmother is coming for dinner.</li>', '<li class="msgpvtstyleme">Dad and I decided to buy you a car.</li>', '<li class="time">17:56</li><li class="msgpvtstyle">Did U? OMG thank U!</li>', '<li class="msgpvtstyleme">No I was just making sure you get my texts.</li>', '<li class="msgpvtstyle">That was cruel</li>']; (function add_msg(){if(!msgs.length)return;$('.messagepvt').append(msgs.shift());style_latest_messages();setTimeout(add_msg,(msgs[0] || "").length * 50)})();
.messagepvt{ position: absolute; top: 0; left: 50%; height: 100%; overflow: hidden; margin-left: -35%; list-style: none; font-family: Arial, Helvetica, sans-serif; width: 70%; margin-top: 0; background: #f5f5f5; padding: .5em }body{ overflow: hidden }.messagepvt:after{ content: ""; display: block; clear: both }.time{ text-align: center; clear: both; color: #888; font-size: 10px; margin: .5em }.msgpvtstyle, .msgpvtstyleme { padding: .3em .8em; float: left; clear: both; background: #e6e6ec; color: #000; margin: 1px; font-size: 12px; -webkit-transition: border-radius .25s ease; -moz-transition: border-radius .25s ease; -webkit-animation: deploy .15s ease; -moz-animation: deploy .15s ease; -webkit-transform-origin: top left; -moz-transform-origin: top left }.msgpvtstyle.first { border-radius: 1.5em 1.5em 1.5em .5em }.msgpvtstyle.middle { border-radius: .5em 1.5em 1.5em .5em }.msgpvtstyle.last { border-radius: .5em 1.5em 1.5em 1.5em }.msgpvtstyle.first.middle.last, .msgpvtstyleme.first.middle.last { border-radius: 1.5em 1.5em 1.5em 1.5em }.msgpvtstyleme { float: right; background: #49f; color: #fff; -webkit-transform-origin: top right; -moz-transform-origin: top right}.msgpvtstyleme.first { border-radius: 1.5em 1.5em .5em 1.5em }.msgpvtstyleme.middle { border-radius: 1.5em .5em .5em 1.5em }.msgpvtstyleme.last { border-radius: 1.5em .5em 1.5em 1.5em }#-webkit-keyframes deploy{ from{-webkit-transform: scale(0)}to{-webkit-transform: scale(1)} }#-moz-keyframes deploy{ from{-moz-transform: scale(0)}to{-moz-transform: scale(1)} }
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="messagepvt"></ul>
Try this code to add classes in existing html tags
$('.msgpvtstyle ').each(function() {
$('.msgpvtstyleme:first-child' , $(this)).addClass('first');
$('.msgpvtstyleme:last-child' , $(this)).addClass('last');
$('.msgpvtstyleme:not(:first-child):not(:last-child)' , $(this)).addClass('middle');
});

select list doesn't retain selected value

I created custom <select> styles using jQuery for multiple select boxes in a form. But the <select> boxes don't show if any value pre-selected but always show "Please Select".
$('.custom_select').each(function() {
var list = $(this).children('ul'),
select = $(this).find('select'),
title = $(this).find('.select_title');
title.css('min-width', title.outerWidth());
// select items to list items
if ($(this).find('[data-filter]').length) {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li data-filter="' + select.children('option').eq(i).data('filter') + '" class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
} else {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
}
select.hide();
// open list
title.on('click', function() {
list.slideToggle(400);
$(this).toggleClass('active');
});
// selected option
list.on('click', 'li', function() {
var val = $(this).text();
title.text(val);
list.slideUp(400);
select.val(val);
title.toggleClass('active');
});
});
.select_title {
cursor: pointer;
padding: 2px 39px 3px 9px;
border: 2px solid #e4e4e2;
background: #f5f7f8;
z-index: 1;
min-width: 75px;
-webkit-transition: border-color .4s ease;
-moz-transition: border-color .4s ease;
-o-transition: border-color .4s ease;
transition: border-color .4s ease;
}
.select_list {
cursor: pointer;
width: 100%;
border-left: 2px solid #e4e4e2;
border-right: 2px solid #e4e4e2;
border-bottom: 2px solid #e4e4e2;
-webkit-border-bottom-left-radius: 4px;
-moz-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-moz-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
ul {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="custom_select relative">
<div class="select_title">Please Select</div>
<ul class="select_list d_none" style="display:none;"></ul>
<select name="title" id="title" required style="display:none;">
<option value=""></option>
<option value="Mr." selected="selected">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss</option>
</select>
</div>
How can I get to show if values selected?
I'd simply fetch the initial select value val() and assign it as text to the title container:
title.text(select.val() || 'Please Select');
If the selected value is empty (or no option is selected initialy), it will update title with a standard 'Please Select' text.
JSFiddle
If you want to have more controll over the code you can write the above code widely:
if(select.val()){
title.text(select.val());
// anything else ...
}else{
title.text('Please Select');
// anything else ...
}
Add below js code in your js and check
var text = $('#title').val();
if(text != ""){
$('.select_list li').each(function(){
if(text == $(this).text())
$(this).click();
});
}
$('.custom_select').each(function() {
var list = $(this).children('ul'),
select = $(this).find('select'),
title = $(this).find('.select_title');
title.css('min-width', title.outerWidth());
// select items to list items
if ($(this).find('[data-filter]').length) {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li data-filter="' + select.children('option').eq(i).data('filter') + '" class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
} else {
for (var i = 0, len = select.children('option').length; i < len; i++) {
list.append('<li class="tr_delay_hover">' + select.children('option').eq(i).text() + '</li>')
}
}
select.hide();
// open list
title.on('click', function() {
list.slideToggle(400);
$(this).toggleClass('active');
});
// selected option
list.on('click', 'li', function() {
var val = $(this).text();
title.text(val);
list.slideUp(400);
select.val(val);
title.toggleClass('active');
});
});
var text = $('#title').val();
if(text != ""){
$('.select_list li').each(function(){
if(text == $(this).text())
$(this).click();
});
}
.select_title {
cursor: pointer;
padding: 2px 39px 3px 9px;
border: 2px solid #e4e4e2;
background: #f5f7f8;
z-index: 1;
min-width: 75px;
-webkit-transition: border-color .4s ease;
-moz-transition: border-color .4s ease;
-o-transition: border-color .4s ease;
transition: border-color .4s ease;
}
.select_list {
cursor: pointer;
width: 100%;
border-left: 2px solid #e4e4e2;
border-right: 2px solid #e4e4e2;
border-bottom: 2px solid #e4e4e2;
-webkit-border-bottom-left-radius: 4px;
-moz-border-bottom-left-radius: 4px;
border-bottom-left-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-moz-border-bottom-right-radius: 4px;
border-bottom-right-radius: 4px;
}
ul {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="custom_select relative">
<div class="select_title">Please Select</div>
<ul class="select_list d_none" style="display:none;"></ul>
<select name="title" id="title" required style="display:none;">
<option value=""></option>
<option value="Mr." selected="selected">Mr.</option>
<option value="Mrs." >Mrs.</option>
<option value="Miss.">Miss</option>
</select>
</div>

How to add a small description window when mouse cursor is over a element class?

I tested a method for see if it works, but... no, see:
var classname = document.getElementsByClassName('avatarTestCx');
function myFunction() {
document.write("Test.");
}
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('mouseover', myFunction, false);
}
When the mouse cursor is about a element class, it calls a function to write in document (it's just a test to verify if will be possible do the small description window).
It's not working...
Do you have some method for example?
If it's just a simple tooltip I guess a title attribute would get this done.
Here is a example fiddle http://jsfiddle.net/542jwva8/1/
var classname = document.getElementsByClassName('avatarTestCx');
for(var i=0;i<classname.length;i++){
classname[i].setAttribute("title", "Small description \n Another line");
}
I would go about doing this, by using data-tooltip
Example
Inside this example it'll show a message box when hovering over an element, any questions just ask me
// Create style
var style = document.createElement('style');
document.head.appendChild(style);
// Store matching elements
var matchingElements = [];
// All elements
var allElements = document.getElementsByTagName('*');
// Loop through all elements
for (var i = 0, n = allElements.length; i < n; i++)
{
// All elements with attribute of data-tooltip
var attr = allElements[i].getAttribute('data-tooltip');
if (attr)
{
allElements[i].addEventListener('mouseover', hoverEvent);
}
}
function hoverEvent(event)
{
event.preventDefault();
x = event.x - this.offsetLeft;
y = event.y - this.offsetTop;
// Show value of "this" inside console
console.log(this);
// Make it hang below the cursor a bit.
y += 10;
style.innerHTML = '*[data-tooltip]::after { left: ' + x + 'px; top: ' + y + 'px }'
// Show value of "this" inside console
console.log(this);
}
*[data-tooltip] {
position: relative;
}
*[data-tooltip]::after {
content: attr(data-tooltip);
position: absolute;
top: -20px;
right: -20px;
width: 150px;
pointer-events: none;
opacity: 0;
-webkit-transition: opacity .15s ease-in-out;
-moz-transition: opacity .15s ease-in-out;
-ms-transition: opacity .15s ease-in-out;
-o-transition: opacity .15s ease-in-out;
transition: opacity .15s ease-in-out;
display: block;
font-size: 12px;
line-height: 16px;
background: #fefdcd;
padding: 2px 2px;
border: 1px solid #c0c0c0;
box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.4);
}
*[data-tooltip]:hover::after {
opacity: 1;
}
/* No need for this CSS, just for example purpose */
div {
margin-top: 100px;
background-color: black;
width: 200px;
height: 20px;
}
<div data-tooltip="Test message 1"></div>
<div data-tooltip="Test message 2"></div>

Categories

Resources