I'm looking for a practical way to hide a label of an input type range when its value is lower than a specific number.
And then showing it again when the value goes back to a specific minimum number.
any idea?
Thanks
$('input[type="range"]').on('mouseup', function() {
this.blur();
}).on('mousedown input', function() {
$('#1').text(this.value + "%");
$('#2').text(100 - this.value + "%");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="range" min="0" max="100" step="1" value="50" />
<div class="container2">
<label id="1">50%</label>
</div>
<div class="container3">
<label id="2">50%</label>
</div>
</div>
You can simply use if statement to validate your condition and than use hide() or show() on the element you want to display or not.
In the example below, label with id="2" is shown when value is greater or equal to 50 and hidden when value is lower.
$('input[type="range"]').on('mouseup', function() {
this.blur();
}).on('mousedown input', function() {
var label1value = this.value;
var label2value = 100 - this.value;
$('#1').text(this.value + "%");
$('#2').text(100 - this.value + "%");
// compare value greater or equal to 50
if (this.value >= 50) {
// show element when condition is true
$('#2').show();
} else {
// hide element when condition is false
$('#2').hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="range" min="0" max="100" step="1" value="50" />
<div class="container2">
<label id="1">50%</label>
</div>
<div class="container3">
<label id="2">50%</label>
</div>
</div>
Well, I'm not really sure of what you really want to achieve but here is a code sample and a demo.
The range label disappears when value is lower than 50.
Using Vanilla JS
// On document ready
document.addEventListener("DOMContentLoaded", function() {
// set a range limit to show/hide range label
var rangeLimit = 50;
// When range value changes, call this listener
function rangeValueListener(event) {
var rangeElement = event.target || event.srcElement;
setRangeLabelValue(rangeElement);
}
// Update range label for a range element
function setRangeLabelValue(rangeElement) {
var rangeLabelElement = document.querySelector(
'label[for="' + rangeElement.id + '"]'
);
// Update label text using range value
var rangeValue = rangeElement.value;
rangeLabelElement.innerText = rangeValue + "%";
// if range value is lower than limit, hide it else restore initial state
if (rangeValue < rangeLimit) {
rangeLabelElement.style.display = "none";
} else {
rangeLabelElement.style.display = "initial";
}
}
// Get range element
var rangeElement = document.querySelector("#myRange");
// Attach a listener to change range label when range value change
rangeElement.addEventListener("input", rangeValueListener);
rangeElement.addEventListener("change", rangeValueListener);
// Set initial range label
setRangeLabelValue(rangeElement);
});
Code snippet using jQuery (without explanation, code is simply adapted)
$(document).ready(function() {
var rangeLimit = 50;
var rangeDefaultValue = 65;
function rangeValueListener(event) {
setRangeLabelValue(event.target);
}
function setRangeLabelValue(rangeElement) {
var rangeElementId = rangeElement.id || rangeElement.attr("id");
var rangeLabelElement = $('label[for="' + rangeElementId + '"]');
var rangeValue = rangeElement.value || rangeDefaultValue;
rangeLabelElement.text(rangeValue + "%");
if (rangeValue < rangeLimit) {
rangeLabelElement.hide();
} else {
rangeLabelElement.show();
}
}
var rangeElement = $("#myRange");
rangeElement.on("input change", rangeValueListener);
setRangeLabelValue(rangeElement);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<input id="myRange" type="range" min="0" max="100" step="1" value="65" />
<label for="myRange"></label>
</body>
</html>
Related
How Can I Copy Number entered by the user and show on a Popover via javascript or jquery?
I mean when user typed numbers biger than zero, forexample: 1000, popover Show 1000.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number"
name="price"
id="price"
class="form-control"
min="0"
required />
</form>
</body>
You need to wait for the user to finish typing before you show the number, to do that you need to delay the alert show using a timeout function
$(document).ready(function() {
var timeout;
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
clearTimeout(timeout);
timeout = getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
return setTimeout(function() {
if (!isNaN(price) && price > 0) {
$('[data-content]').attr('data-content',price);
$('[data-toggle="popover"]').popover('show');
}
}, 400);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required data-toggle="popover" data-placement="bottom" data-content="0"/>
</form>
</body>
You can do it on blur event.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("blur", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required />
</form>
</body>
What this program its supposed to do is first with a range input you put how many elements you want to guess then it will show a random element form a json list and you have to guess the valnce and then it will load annother one and you continue. OK when i run this code everything is normal until you click submit button two times. When i click the submit botton the first time its goes well but the second time the program runs the if in the line 41 but it also runs the code in the else and if you submit more times it will run the alerts more and more times.
I have tried doing it other ways like just putting all into a for but it still runing code i dont want to.
const $ = require('jquery');
let elementoActual;
let valorPositivoCorrecto;
let valorNegativoCorrecto;
let valorCuadroNegativo;
let valorCuadroPositivo;
// Button on click add the element
$(document).ready(function() {
$("#startButton").click(function() {
$(".hide").hide();
let questionHTML = '<div class="elementoQuimico"><img id="imgElemnt" src="" alt=""></div>' +
'<div class="valenciasElemento">' +
'<input type="text" class="valorPositivo" placeholder="Valencias positivas">' +
'<input type="text" class="valorNegativo" placeholder="Valencias negativas">' +
'</div>' +
'<button class="submitButtonElement">SUBMIT</button>';
$(".questions").append(questionHTML);
putAnElement();
}); //onclick ends
}) //ready ends
function putAnElement() {
let numb = $("#textInput").val();
let counter = 0;
$.getJSON("../../json/valencias.json", function(data) {
let numeroDeElemento = Math.floor(Math.random() * 3);
elementoActual = data[numeroDeElemento];
valorNegativoCorrecto = data[numeroDeElemento].valenciasNegativas;
valorPositivoCorrecto = data[numeroDeElemento].valenciasPositivas;
//$("#imgElemnt").attr( "src" , elementoActual.img);
$("#imgElemnt").attr("alt", elementoActual.name);
$("#imgElemnt").attr("width", "200px");
$("#imgElemnt").attr("height", "200px");
alert(numb);
$(".submitButtonElement").click(function() {
valorCuadroNegativo = $(".valorNegativo").val();
valorCuadroPositivo = $(".valorPositivo").val();
$(".valorNegativo").val("");
$(".valorPositivo").val("");
if (valorCuadroNegativo === valorNegativoCorrecto &&
valorCuadroPositivo === valorPositivoCorrecto) {
alert("correcto");
counter++;
alert(counter);
if (counter != numb){
putAnElement();
} else {
alert("ya");
}
} else {
alert("incorrecto");
counter++;
alert(counter);
if (counter != numb) {
putAnElement();
} else {
alert("ya");
}
}
});
}); //getJSON ends
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tabla periodica</title>
<link rel="stylesheet" href="../../css/periodic-table.css">
</head>
<body>
<div class="wrapper">
<div class="hide">
<h1>TABLA PERIODICA</h1>
<img src="../../img/tabla-valencias.png">
<div class="buttons">
<button id="startButton">EMPEZAR</button>
<form id="submit-tabla">
<label for="rangeInput"></label><input type="range" name="amountRange" id="rangeInput" min="10" max="30" value="20" oninput="this.form.amountInput.value=this.value" />
<label for="textInput"></label><input type="number" name="amountInput" id="textInput" min="10" max="30" value="20" oninput="this.form.amountRange.value=this.value" />
</form>
</div>
</div>
<div class="questions">
</div>
</div>
<footer>
2017 © Nestor and Diego
</footer>
<script src="chemistry.js"></script>
</body>
</html>
And here is the json
[
{
"name":"hidrogeno",
"valenciasNegativas":"-1",
"valenciasPositivas":"1",
"img":"img/Hidrogeno.svg"
},
{
"name":"litio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Litio.svg"
},
{
"name":"sodio",
"valenciasNegativas":"",
"valenciasPositivas":"1",
"img":"img/Sodio.svg"
}
]
I have 2 products and wanted to multiply with quantity and add up both price along with tax and to show the final price of both added and multiplied values I tried doing using jQuery but I am unable to multiply and add up both values can any one help me out
Here is the code for it:
$(document).ready(function(){
$('#sticker01').on('keyup', function() {
var sticker_01 = $('#sticker01').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_01 * 8 +1.30) + oldval;
$('#order_total').html(total_val);
});
});
$(document).ready(function(){
$('#sticker02').on('keyup', function() {
var sticker_02 = $('#sticker02').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_02 * 2 + 1.30) + oldval;
$('#order_total').html(total_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $<div id="order_total">0.00</div></span>
</div>
Here is a less verbose solution to your issue with minor changes to the HTML and a complete overhaul of the Javascript.
HTML:
I added the min attribute and set its value to 0 to prevent the input spinners from selecting negative values in both the sticker01 and sticker02 elements. I also set the order_total input to disabled as this is the calculation field which will get its value from the inline Javascript. These udpates are cosmetic and play no roll in the structural performance your app.
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
Javascript:
Here you can implement an anonymous function to handle the events .keyup() and .change() and use a delegated event on the input elements.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
That's everything you need. Here is a sample Code Snippet for your review.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
I'm trying to sum up values of buttons if the buttons are clicked on. For example, there is "Button1". If this button is clicked, it should add its value to a sum which will be displayed at the bottom of the page. If "Button1" is clicked a second time it should substract its value from the sum.
Here is my attempt to do this but it's not doing anything at all:
var value_Buttons = 0;
var total = 0;
$("button[name=Button1],[name=Button2],[name=Button3],[name=Button4],[name=Button5],[name=Button6]").click(function() {
if($(this).hasClass('active') == false) {
value_Buttons += parseInt($(this).val());
} else if($(this).hasClass('active') == true) {
value_Buttons -= parseInt($(this).val());
}
total += value_Buttons;
alert(total);
});
total = value_Buttons + value_Optional_Button;
$("input[name=value_sum]").val(total);
Additionally, here is the code for an examplary button (Like "Button1"):
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button1" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">Button 1</button>
</div>
There will be more buttons, but they will only differ in their name and value.
Also, the box which will display the sum of the button-values currently looks like this:
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
I've searched all over Stackoverflow, as well as via Google, etc. yet I can't find anything or anyone with a similar problem
Blocking JS logic error is here :
$("input[name=value_sum]").val(total);
this line should be in the above code block. Added corrections for substraction :
var total = 0;
$("button[name]").on("click", function() {
if(!$(this).hasClass('active')) {
total += Number($(this).val());
$(this).addClass('active').html("remove " + $(this).attr("title"));
} else {
total -= Number($(this).val());
$(this).removeClass('active').html("add " + $(this).attr("title"));
}
$("input[name=value_sum]").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button300" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 300 €</button>
<button type="button" class="form-control btn btn-primary" name="Button600" value="600" title="600 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 600 €</button>
</div>
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
Lines 14 and 15 need to be placed within the click event of the button to update the value_sum input on every click. Also your selection for the value attribute it a little bit off. The way to return the value attribute of a button using jQuery is:
$(this).attr('value');
So after these two points, stripping your code of the if and else check, and also selecting the buttons with a cleaner method, you should have something like this:
var total = 0;
$("button[name=Button1], button[name=Button2], button[name=Button3], button[name=Button4], button[name=Button5], button[name=Button6]").click(function() {
total += $(this).attr('value');
$("input[name=value_sum]").val(total);
});
To display the total, that is 0, in the input element on page load, you could use:
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
start off by create a listener for a class that will be applied to all of your buttons.
$(.btn).click(function() {
//get value
var value = parseint($(this).attr("value"));
//check if already clicked
if($(this).hasClass('active') {
//set value of total
total = total - value;
//remove class active
$(this).removeClass('active');
}else {
//set value of total
total = total + value;
//addclass active
$(this).addClass('active');
}
)};
Is this what you need?
Working Demo
Here have added a classname 'add' for all buttons , on click its toggle class add, sub in you case you using active,inactive class
var total = 0;
$("button[name=button1],[name=button2],[name=button3]").on('click', function () {
var self = $(this);
var gValue = Number(self.val());
if (self.hasClass("add")) {
total += gValue;
self.removeClass("add").addClass("sub");
} else {
total -= gValue;
self.removeClass("sub").addClass("add");
}
$("#costs").val(total);
});
Check this fiddle.
Add as many buttons as you like, the only thing is that you'll have to add a data-value to them to figure out how much to add or substract. I would also do the search for buttons using a class instead of "button" but that's up to you.
var buttons = {};
$("button").each(function (index, item) {
buttons[index] = 0;
$(item).click(function () {
var value = +($(item).data("value")),
val = +($("#costs").val());
val += (!buttons[index]) ? value : -value;
buttons[index] = (!buttons[index]) ? 1: 0;
$("#costs").val(val);
});
});
Hope it helps.
I have made a page using jquery, and on load it selects the first text field automatically. I want it to then move to the next field when the ENTER key is pressed.
$('.barcodeField input').bind('keyup', function(event) {
if(event.keyCode==13){
$("this + input").focus();
}
});
I can't find anything that works on the net. And I've scoured the forums.
I've created a little function which can do what you need. This is the version I use so you may need to change the class names but you should get the idea.
<script type="text/javascript">
$(document).ready(function(){
$(".vertical").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
</script>
So basically:-
Get all the input fields matching .vertical
Find which is the current text box
Find the next one
Set the focus on that one
You should use:
$(this).next('input').focus();
try this:
(function($){
$.fn.enterNext = function(){
var _i =0;
$('input[type=text], select',this)
.each(function(index){
_i = index;
$(this)
.addClass('tab'+index)
.keydown(function(event){
if(event.keyCode==13){
$('.tab'+(index+1)).focus();
event.preventDefault();
}
});
})
$( "input[type=submit]",this ).addClass('tab'+(_i+1));
}})(jQuery);
for use:
$('form.element').enterNext();
in my case this is the best solution in that I got because the function .next() is strict with elements outside their branch DOM.
The best way is to force an index.
and sorry for my bad English...
Basically, you just need top have the DOM elements in some structure so that you can select the next one. I'd suggest exploiting tabindex, but anything that let's you have a defined order will work.
Here is the solution I came up with. The issue I had was that I needed to maintain tabindex, i.e. it had to function exactly that same as hitting tab. It uses both underscore and jquery.
I've left in my debugging code:
try {
var inputs = $("input[id^=tpVal-]");
var sortedInputs = _.sortBy(inputs, function(element){
var tabIndex = $(element).attr('tabindex');//debugging
var id = $(element).attr('id');//debugging
console.log(id +" | "+ tabIndex +" | "+ $(element));//debugging
return parseInt($(element).attr('tabindex'));
});
$(sortedInputs).each(function (index, element) {
$(element).keyup(function(event){
if(event.keyCode==13) {
var $thisElement = $(element);//debugging
var nextIndex = index+1;//debugging
var $nextElement = $(sortedInputs[nextIndex]);
var thisId = $thisElement.attr('id');//debugging
var nextId = $nextElement.attr('id');//debugging
console.log("Advance from "+thisId+" to "+nextId);//debugging
if($nextElement!=undefined) {
$(sortedInputs[index + 1]).focus();
}
}
});
});
} catch (e) {
console.log(e);
}
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input type="text" name="abc" /><br>
<input type="text" name="abc1" /><br>
<input type="text" name="abc2" /><br>
<input type="text" name="abc3" class='TabOnEnter' tabindex="3" /><br>
<input class='TabOnEnter' tabindex="4" /><br>
<input class='TabOnEnter' tabindex="5" /><br>
<input class='TabOnEnter' tabindex="6" /><br>
<!-- <textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>-->
<input type="submit" value="submit" class='TabOnEnter' tabindex="7">
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on("keypress", ".TabOnEnter", function (e)
{
//Only do something when the user presses enter
if (e.keyCode == 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut(); })
</script>
</body>
</html>
This code works for me
HTML:
<div class="row">
<div class="col-md-3"> Name </div>
<div class="col-md-3"> <input type="text" /> </div>
</div>
<div class="row">
<div class="col-md-3"> Email</div>
<div class="col-md-3"> <input type="email" /> </div>
</div>
Jquery code:
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
$(this).parent().parent().next('div').find('input').focus();
}
});