<div class="range-wrap">
<input id="range" type="range" name="range" min="3" max="20" value="10" step="1">
<label id="rangevalue">10</label>
</div>
I to need to create range slider, where the values below 7 are labelled modest, 7 to 15 as moderate and anything above labelled as extensive. How I do add these labels to my range slide?
The idea will to be just simply get the value of existing slider and based on the value, do an if statement.
And to get the value when someone moves the slider, you can use oninput.
Try this:
First Answer Without The Partition
var slider = document.getElementById("range");
var display = document.getElementById("display");
var getVal = slider.value;
numVal.innerHTML = getVal; // If you don't want the number to be displayed, delete this. This is to show at which number the label will change
if(getVal<7) {
display.innerHTML = "Modest";
}
if(getVal>=7 && getVal<=15) {
display.innerHTML = "Moderate";
}
if(getVal>15){
display.innerHTML = "Extensive";
}
slider.oninput = function() {
numVal.innerHTML = this.value;// If you don't want the number to be displayed, delete this. This is to show at which number the label will change
var getVal = this.value;
if(getVal<7) {
display.innerHTML = "Modest";
}
if(getVal>=7 && getVal<=15) {
display.innerHTML = "Moderate";
}
if(getVal>15){
display.innerHTML = "Extensive";
}
}
<div class="range-wrap">
<input id="range" type="range" name="range" min="3" max="20" value="10" step="1">
<label id="display"></label>
<p id="numVal"></p> <!-- If you don't want the number to be displayed, delete this. This is to show at which number the label will change -->
</div>
ps: I've added comments in the code to hide the number if you don't want it. The numbers are there so you can see the change is happening at the right number. Delete the commented code accordingly to hide number values from displaying.
Updated Answer: (with partition)
You can use child elements to create a bar and push it on top of the slider using absolute and relative position. Its just a simple CSS trick.
The idea is to set a width for your range. Then, create 2 divs that looks like bars using border-right and then absolutely position it to your parent (which would be the range input)
Try this:
var slider = document.getElementById("range");
var display = document.getElementById("display");
var getVal = slider.value;
numVal.innerHTML = getVal; // If you don't want the number to be displayed, delete this. This is to show at which number the label will change
if(getVal<7) {
display.innerHTML = "Modest";
}
if(getVal>=7 && getVal<=15) {
display.innerHTML = "Moderate";
}
if(getVal>15){
display.innerHTML = "Extensive";
}
slider.oninput = function() {
numVal.innerHTML = this.value;// If you don't want the number to be displayed, delete this. This is to show at which number the label will change
var getVal = this.value;
if(getVal<7) {
display.innerHTML = "Modest";
}
if(getVal>=7 && getVal<=15) {
display.innerHTML = "Moderate";
}
if(getVal>15){
display.innerHTML = "Extensive";
}
}
#range-wrap {
position: relative;
}
input[type=range] {
width: 200px;
}
#range-bars {
width: 1px;
height: 10px;
border-right: 2px solid black;
position: absolute;
top: 13px;
left: 47px;
}
#range-bars-two {
width: 1px;
height: 10px;
border-right: 2px solid black;
position: absolute;
top: 13px;
left: 157px;
}
<div class="range-wrap">
<input id="range" type="range" name="range" min="3" max="20" value="10" step="1">
<label id="display"></label>
<p id="numVal"></p> <!-- If you don't want the number to be displayed, delete this. This is to show at which number the label will change -->
<div id="range-bars"></div>
<div id="range-bars-two"></div>
</div>
ps: there was a slight error in the if statement and I have made the changes to this answer plus the snippet 1 answer.
Related
I've got a text box that the user inputs a hex value for a colour. The text box will change colour to the hex value entered, however the problem is that if the input is a shade of black, or any dark colour, it is very difficult, or impossible to see what hex value has been entered. So I want the inputted text to have a different coloured outline, for example white so the user is clearly able to see what they have entered.
This is a part of my code:
<head>
<style>
#ColourInput { /* apply this style to element id="ColourInput" */
left: 240px;
top: 60px;
width: 100px;
}
input[type=text]:focus {
border: 3px solid #555;
</style>
<script>
function fnCustomColour() {
var sHexValue = document.getElementById("ColourInput").value;
var ValueValid = 0
fnDebugMessage(sHexValue);
if (/[0-9A-F]{6}$/i.test(sHexValue)) {
if (sHexValue.indexOf("#") === 0) {
} else {
sHexValue = "#"+sHexValue
}
ValueValid = 1
} else {
alert("Value not allowed");
ValueValid = 0
}
if (ValueValid = 1) {
ColourInput.style.backgroundColor = sHexValue;
fnSetFillColour(sHexValue);
fnDebugMessage(sHexValue);
}
}
</script>
</head>
<div id="CustomColour">
Custom Colour Input: #<input type="text" id="ColourInput" name="CustomColour" placeholder="Enter Hex Value" pattern="[a-fA-F0-9]{8}$/i"><br>
<input type="submit" onclick="fnCustomColour();" id="ColourSubmit" value="Submit">
</div>
Any help will be appreciated
On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
When i create a new dynamic div it is overlapping with previously created div.
Below is the CSS i've used
.dynamictextbox{
width:50%;
position:relative;
padding:10;
}
.dynamictextbox .mytxt{
position:absolute;
left:0px;
right:50%;
}
.dynamictextbox .mytext{
position:absolute;
left:51%;
right:100%;
}
Below is the HTML code
<div id="Enter your name" class="dynamictextbox">
<label class="mytxt">Enter your name</label>
<input type="text" name="Enter your name_name" id="Enter your name_id" class="mytext">
</div>
<br />
<div id="bigData" class="dynamictextbox">
<label class="mytxt">Now this is a long text which will overlap the next div.Need solution for this. Please give me a solution for this</label>
<input type="text" name="bigData_name" id="bigDate_id" class="mytext">
</div>
<br />
<div id="div_temp" class="dynamictextbox">
<label id="txtlb" class="mytxt">Dynamic Label</label>
<input type="text" name="tb" id="tb" class="mytext">
</div>
<br />
What you need here, is to expand the element according to the content height. Unfortunately you cannot do this using CSS. So we'll have to move along with javascript.
Here goes the script
<script>
var max = 0;
function setHeight() {
var elements = document.getElementsByClassName('mytxt');
var height = 0;
for (var i = 0; i < elements.length; i++) {
height = elements[i].scrollHeight;
if (height > max) {
max = height;
}
}
elements = document.getElementsByClassName('dynamictextbox');
for (var i = 0; i < elements.length; i++) {
elements[i].style = "min-height: " + max + "px";
}
}
</script>
At the end of all the divs call the funtion setHeight().
<script>setHeight()</script>
So the output will look like this
P.S. I've added borders to the class dynamictextbox for testing purposes.
This may be helpful - JSFIDDLE
Just remove the .mytxt class from your CSS and increase the left attribute of .mytext class
.dynamictextbox .mytext{
position:absolute;
left:60%;
right:100%;
}
Update the code below. Is this what you where going after?
$("#add").on("click", function(){
// just a helper function for some random content
function dynamicText(){
var min = 1;
var max = 50;
var random = Math.floor(Math.random() * max) + min;
var text = "";
for(var i = 0; i < random; i++){
text += "text ";
}
return text;
}
// add to the container
var addMe = "\
<div class='dynamictextbox'>\
<label class='mytxt'>"+dynamicText()+"</label>\
<textarea class='mytext'>"+dynamicText()+"</textarea>\
</div>\
";
var container = $("#container");
container.append(addMe);
});
.dynamictextbox{
width:50%;
padding:10;
margin-top: 10px;
background: #CCC;
overflow: auto;
}
.dynamictextbox .mytxt{
position: relative;
float: left;
width: calc(50% - 10px);
}
.dynamictextbox .mytext{
float: right;
width: calc(50% - 10px);
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
<br><hr><br>
<button id="add">ADD</button><br><br>
<div id="container"></div>
Here I want to randomly change the CSS of each character of text.
Like if I input Stack I will get S in red, t in blue, a in green... etc on the bottom of the input field.
var myModel = {
name: "Mayur",
};
var myViewModel = new Vue({
el: '#my_view',
data: myModel
});
span{
color:green;
font-weight:600;
font-size:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="my_view">
<label for="name">Enter name:</label>
<input type="text" v-model="name" id="name" name="name" />
<p>Welcome, <span>{{ name | uppercase }}</span></p>
</div>
I haven't worked with Vue and I'm not familiar with its internal events and processes, but here's a tiny prototype i made in plain JavaScript:
document.querySelector('button').onclick = function (){
let span = document.querySelector('span.letters'),
text = span.textContent;
span.innerHTML = '';
Array.from(text).map(function(l){
let color = document.createElement('span');
color.innerHTML = l;
color.style.color = 'rgb(' +
randInterval(0, 255) + ',' +
randInterval(0, 255) + ',' +
randInterval(0, 255) + ')';
span.appendChild(color);
});
}
function randInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
<div><span class="letters">STACK</span></div>
<button>Random colors</button>
I've purposefully placed the function that randomizes each value of rgb() in a function, so you can alter it easily (now the colors are trully random). If you want to make the darker, you need to lower the max values. If you want the colors lighter, you need to increase the mins.
Html:
<div>Type something here, then click on the white space beneave.</div>
<input type="hidden" id="hidden">
Javascript:
$("div").prop("contentEditable", true).blur(function(){
var chars = $(this).text().split("");
$("#hidden").val($(this).text());
this.innerHTML = "";
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16)
}).appendTo("div");
});
});
Css:
div{
border: 1px solid black;
width: 400px;
height: 20px;
padding: 2px 3px;
overflow: hidden;
}
You can visit http://jsfiddle.net/DerekL/Y8ySy/ for the implementation!
Both html and css codes are given in the link.
It gives the colour to the characters randomly but it can be manipulated easily or if you want them to run randomly, you can use it directly.
I have created a modal with checkboxes that when checked, are added to the DOM. The issues that I am having that I have been trying to troubleshoot for days are that whether the checkboxes are checked or unchecked, the tag is added to the DOM, not just when checked.
I also cannot figure out how to remove the tag from the DOM when the associated checkbox is unchecked. I have the amount of checkboxes that are able to be checked max out at 6, which is what I am looking to have, but is there a way to max the amount of child divs within a parent div there could be? That way theres another safeguard to fall back on so that no more than 6 tags can be selected at one time?
Here is a jsfiddle http://jsfiddle.net/co5w7c9j/ with what I have, hopefully I explained enough without making it sound too confusing.
Below is my jquery that I have written thus far, I think I am missing a step somewhere to achieve what I am looking for.
Thank you for taking the time to look through my code.
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
/* if ($('.Specialties > .specTag').has(('[name=specialty]:checked').attr('value'))) {
$('.Specialties > .specTag').has((this).txt()).remove();
} */
// Count number of checkboxes selected and display in modal
var increment = 0;
$('[name=specialty]:checked').each(function() {
if (this.checked) {
increment++;
} else {
increment--;
}
$('#specCount').html(increment);
});
// Disable checkboxes when 6 (maximum) are selected
$("input[type=checkbox][name=specialty]").click(function() {
var bol = $("input[type=checkbox][name=specialty]:checked").length >= 6;
$("input[type=checkbox][name=specialty]").not(":checked").attr("disabled", bol);
});
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function() {
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
});
Try
// When specilaty is checked, add tag to profile page
$('input[name=specialty]').change(function() {
var value = this.value;
//if checked add a new item else remove item.
if (this.checked) {
var $newTag = $("<div class='specTag'>" + value + "<div class='xOut'>x</div></div>").attr('data-id', value);
$('.Specialties').append($newTag);
} else {
//use the attribute value which is the same as the input value to find out the item to be removed
$('.Specialties').find('div.specTag[data-id="' + value + '"]').remove()
}
//cache the result since it is used multiple times
var $checked = $('input[name=specialty]:checked');
// Count number of checkboxes selected and display in modal
var increment = $checked.length;
$('#specCount').html(increment);
// Disable checkboxes when 6 (maximum) are selected
var bol = increment.length >= 6;
//use prop instead of attr to set the disabled state
$("input[type=checkbox][name=specialty]").not(":checked").prop("disabled", bol);
// Create array of checked items - add on checked - remove on uncheck
var specialtyArray = $checked.map(function() {
return $(this).val();
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().prop('checked', false);
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow', function() {
$(this).remove();
});
//uncheck the corresponding checkbox
$('input[name=specialty][value="' + $(this).closest('.specTag').attr('data-id') + '"]').prop('checked', false)
});
.Specialties {
background-color: #FFFFFF;
width: 350px;
height: 135px;
margin-left: 249px;
margin-top: 125px;
top: 0;
position: absolute;
z-index: 1;
}
.specTag {
background-color: #51b848;
color: #FFFFFF;
font-weight: 200;
letter-spacing: 1px;
font-size: 12px;
width: 150px;
height 30px;
padding: 8px;
position: relative;
margin-left: 10px;
margin-bottom: 5px;
border-radius: 5px;
display: inline-block;
}
.xOut {
background-color: #FFFFFF;
width: 25px;
padding: 3px;
position: absolute;
right: 5px;
text-align: center;
color: #333333;
top: 5px;
border-radius: 0 3px 3px 0;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="GET" id="updateSpecForm">
<!-- ATHLETIC TRAINER OPTIONS -->
<div class="columns" id="athleticTrainer">
<input type="checkbox" name="specialty" value="Boot Camp" />Boot Camp
<br />
<input type="checkbox" name="specialty" value="Children's Fitness" />Children's Fitness
<br />
<input type="checkbox" name="specialty" value="Circuit Training" />Circuit Training
<br />
<input type="checkbox" name="specialty" value="Core Training" />Core Training
<br />
<input type="checkbox" name="specialty" value="Cycling/Spinning" />Cycling/Spinning
<br />
<input type="checkbox" name="specialty" value="Dance" />Dance
<br />
<input type="checkbox" name="specialty" value="Flexibility/Balance" />Flexibility/Balance
<br />
<input type="checkbox" name="specialty" value="Meal Planning" />Meal Planning
<br />
<input type="checkbox" name="specialty" value="Men's Fitness" />Men's Fitness
<br />
<input type="checkbox" name="specialty" value="Women's Fitness" />Women's Fitness
<br />
</div>
<div class="Specialties">
<!-- SHOW BELOW DIV ONLY IF LOGGED IN -->
<!-- <div class="updateOn">+ Update My Specialties</div> -->
<!-- ***PRO CAN ADD UP TO 6 SPECIALY TAGS*** -->
</div>
</form>
Sometimes it's easier to compartmentalize code by setting parts of it into functions so that conditional aspects are easier to read through .
The biggest issue in your code was not testing if checkboxes were checked or not in the click handler.
Since the checkbox needs to do the same as the click on new tag does when it is unchecked, all logic flows through the change event of checkbox. Note that the click handler on X of tag triggers the change also
var maxChecked = 6;
// use change handler on checkboxes, will get triggered also below in another click handler
var $checkboxes = $('[name=specialty]').change(function() {
var value = $(this).val();
if(this.checked ){
addTag( value);
}else{
removeTag( value );
}
checkBoxStatus();
});
function removeTag(checkBoxValue){
/* we stored the checkbox value as data attribute, use that to filter*/
$('.specTag').filter(function(){
return $(this).data('value') === checkBoxValue;
}).slideUp(function(){
$(this).remove();
})
}
function addTag( checkBoxValue){
$newTag = $("<div class='specTag'>" + checkBoxValue + "<div class='xOut'>x</div></div>");
/* store the value in elment data so we can reference back to checkbox */
$newTag.data('value', checkBoxValue);
$('.Specialties').append($newTag);
}
/* use this to both disable and enable checkboxes */
function checkBoxStatus(){
var limitReached = $checkboxes.filter(':checked').length === maxChecked;
$checkboxes.not(':checked').prop('disabled',limitReached);
}
$(document.body).on('click', '.xOut', function () {
var $element = $(this).parent(),
$checkbox = $checkboxes.filter(function(){
return this.value === $element.data('value');
/* trigger change to remove element and reset disabled checkboxes */
}).prop('checked',false).change();
});
DEMO
Working fiddle:
http://jsfiddle.net/co5w7c9j/1/
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
EnableDisableCheck();
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function(){
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {
}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function () {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function () {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
var text = $(this).parent().text();
$('[name=specialty]:checked').filter(function () {
return text.indexOf($(this).val()) > - 1;
}).removeAttr('checked');
EnableDisableCheck();
});
function EnableDisableCheck(){
if($('[name=specialty]:checked').length >=5)
{
$('[name=specialty]').attr("disabled","disabled");
}
else
{
$('[name=specialty]').removeAttr("disabled");
}
}
How can create a mask input for number that have percent by jQuery? Do I make input just accept until three numbers and put percent sign after numbers while user finished typing(keyup)?
I don't use plugins.
Example:
1% Or 30% Or 99% Or 100% Or 200%
<input name="number" class="num_percent">
You're better off not using JavaScript for this. Besides the problems that come with using onkeyup for detecting text input, you also have the hassle of parsing the resulting string back to a number in your client/server scripts. If you want the percent sign to look integrated, you could do something like this:
<div class="percentInput">
<input type="text" name="number" class="num_percent">
<span>%</span>
</div>
.percentInput { position:relative; }
.percentInput span { position: absolute; right: 4px; top:2px; }
.num_percent { text-align: right; padding-right: 12px; }
http://jsfiddle.net/BvVq4/
I'm rushing slightly, so you may have to tweak the styles to get it to look right cross-browser. At least it gives you the general idea.
I've stayed with input number, moved the percentage char and then modified its position according to the length of the input (the amount of digits).
HTML
<input type="number" min="0" max="100" value="100"> //chose 100 only for the sake of the example
<span class="percentage-char">%</span>
CSS
input {
width: 55px;
height: 20px;
font-size:18px;
}
.percentage-char {
position: absolute;
left: 32px; // default position - in this case 100
top: 1px;
font-size: 18px;
}
.one-digit { //position of the '%' when input is 0-9
left: 13px;
}
.two-digits{ //position of the '%' when input is 10-99
left: 24px;
}
JS
$(":input").change(function() { //listening to changes on input
if ($(this).val() < 10) { //adding and removing the classes
$('.percentage-char').removeClass('two-digits');
$('.percentage-char').addClass('one-digit');
} else if ($(this).val() > 9 && $(this).val() < 100) {
$('.percentage-char').addClass('two-digits');
} else {
$('.percentage-char').removeClass('one-digit two-digits');
}
});
Check out this fiddle
function setPercentageMask() {
let input = $('.percent');
input.mask('##0,00', {reverse: true});
input.bind("change keyup", function() {
isBetweenPercentage($(this));
});
}
function isBetweenPercentage(input) {
let myNumber = (input.val()) ? parseFloat(input.val()) : 0;
(myNumber.isBetween(0, 100.00)) ? myNumber : input.val('100,00');
}
if (typeof(Number.prototype.isBetween) === "undefined") {
Number.prototype.isBetween = function(min, max, notBoundaries) {
var between = false;
if (notBoundaries) {
if ((this < max) && (this > min)) between = true;
} else {
if ((this <= max) && (this >= min)) between = true;
}
return between;
}
}
setPercentageMask();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<input name="text" class="percent">