Expected to $('input[type=range]').val() return empty value (If value='').
But, jQuery the return 50% of the (min+max) of the range input element.
https://jsfiddle.net/maheshwaghmare/f33Ljjty/
Any solutoin to detect empty value of input[type=range] element though jQuery?
Input type range Default return value is the range of the number ,not value of attribute .if you need ah value attr .try with attr('value')
$(document).ready(function() {
if(!$('.one').attr('value').trim() || !$('.two').attr('value').trim()){ // validate the attribute value
console.log('any one range attr value is empty')
}
var rangeOne = 'Defult One: ' + $('.one').val() + '<br/>';
var rangeTwo = 'Defult Two: ' + $('.two').val() + '<br/>';
$('.result').html( rangeOne + rangeTwo );
});
body {
padding: 5px;
}
label {
font-weight: bold;
}
input[type=text] {
width: 20em
}
p {
margin: 1em 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Range One <input class="one" min="768" step="1" max="1920" type="range" value=""> (min='768' step='1' max='1920' value='')<br/>
Range Two <input class="two" min="768" step="1" max="1920" type="range" value="800"> (min='768' step='1' max='1920' value='800')
<br/><br/><br/>
<span class="result"></span>
Related
var inpts = $('.map-form .val-input');
var radio = $('.map-form .radio-input');
var counter = $('.filtr-map-count');
$('.detect-change').change(function() {
countInputs();
});
function countInputs() {
var click = 0;
$(inpts).each(function(){
if($(this).val() != ""){
click++;
}
counter.text(click);
});
$(radio).each(function() {
if($(this).val() != ""){
click++;
}
counter.text(click);
});
};
$(window).on('load', function() {
countInputs();
});
.filtr-map {
background-color: red;
width: 100px;
height: 40px;
color: #fff;
z-index: 99;
font-weight: bolder;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
margin-top: 50px;
}
.filtr-map-count {
font-size: 10px;
position: relative;
top: -5px;
left: 5px;
background-color: #000;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class='map-form'>
<div>
<h2>Search</h2>
<fieldset>
<label>Price</label>
<span>min</span>
<input type="text" class='val-input detect-change ' value="" />
<span>max</span>
<input type="text" class='val-input detect-change ' value="" />
</fieldset>
<fieldset>
<label>Category</label>
<div class="styled_select">
<select class='val-input detect-change '>
<option value="">Default</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
</fieldset>
<fieldset>
<div class="styled_radio"><input class='radio-input detect-change' checked="checked" type="radio" id="Radio1" name="Radio" /><label
class="input" for="Radio1"><span class="circle"><span></span></span><span>Test One Test</span></label></div>
<div class="styled_radio"><input class='detect-change' type="radio" id="Radio2" name="Radio" /><label class="input"
for="Radio2"><span class="circle"><span></span></span><span>Test test</span></label></div>
</fieldset>
<input type="submit" value='Send'>
</div>
</form>
<div class="filtr-map">
Filter<span class='filtr-map-count'>0</span>
</div>
Hey, How to get counter when inputs, select etc. change in form? How to make a counter. If input/select/radio change in fieldset counter should increase, if back to default value decrease. The counter number should also works after page reload. I added a js code with im working on but something goes wrong.
---UPDATE---
I added working jquery code for this example, maybe will be helpful for someone else. Also I added classes that help with select the changed elements.
Ok so this becomes a little more complicated if you're considering all input types.
I have written the code below as a starting point. Yes, it does do what you need it to. BUT it hasn't been fully tested and it can be improved.
See a working example here: https://jsfiddle.net/hber3q0z/
The jQuery that's doing the heavy lifting...
var $form = $('.map-form');
var $counter = $('.filtr-map-count');
var changed = {};
// Listen for an `update` event on counter element
$counter.on('update', function() {
// Update the text value
$(this).text(function() {
var count = 0;
// Loop through the `changed` object and count if value has changed
$.each(changed, function(key, hasChanged) {
if (hasChanged) {
count++;
}
});
// Return count
return count;
});
});
// Find all form inputs
$form.find(':input').each(function(key) {
var $this = $(this);
// Get the input name, else create a temporary name
var name = $this.attr('name') || new Date().getTime().toString() + key;
// Store the original value
var original = $this.val();
// If the input is a checkbox
if ($this.is(':checkbox')) {
// Create a function to get checkbox group values
var checkboxValue = function() {
var values = [];
// Find all `checked` inputs with the same type and name
$form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').each(function() {
// Push values to array
values.push($(this).val());
});
// Join them for easier comparisom
return values.join(',');
};
// Store original group value
original = checkboxValue();
// Listen to checkbox events
$this.on('change keyup keydown mouseup', function() {
// Perform value changed check
changed[name] = checkboxValue() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
// If the input is a radio
else if ($this.is(':radio')) {
// Create a function to get radio group value
var radioValue = function() {
// Find the first `checked` input with the same type and name
return $form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').val();
};
// Store original group value
original = radioValue();
// Listen to radio input events
$this.on('change keyup keydown mouseup', function() {
// Perform value changed check
changed[name] = radioValue() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
// Catch-all other input types
else {
// Listen to input events
$this.on('change keyup keydown cut paste', function() {
// Perform value changed check
changed[name] = $this.val() !== original;
// Tell the counter element to update contents
$counter.trigger('update');
});
}
});
The code is checking all inputs in the form for an actual changed value, not just a change event. I have also included support for checkbox and radio groups.
I started to learn javascript 2 weeks ago. I want to do my first program which counts all prices from checked input.
But i dont have idea how to do this.
I found something on internet and stackoverflow, but i dont know to do this for my inputs.
Could you help me?
My code
// this function counts all the values
function showPrice() {
var priceOne = document.getElementsByName('price1');
var priceTwo = document.getElementsByName('price2');
var priceThree = document.getElementsByName('price3');
}
You can do this by getting a list of elements for all the inputs, check the ones that are checked, get their values, convert them to numbers and sum them.
Beginning with a list of ids, use Array.map() to transform the list into a list of string ids (1 -> test1).
Then apply getElementById() to each id to get the HTML element.
Then from the element extract and convert the value if the input is checked, otherwise map the element to 0.
Use Array.reduce to sum the values.
Using getElementById, find your output span and set its innerHTML to the total.
function showPrice() {
const total = [1,2,3,4,5,6,7,8,9]
.map(id => `test${id}`)
.map(id => document.getElementById(id))
.map(el => el && el.checked ? Number(el.value) : 0)
.reduce((sum, value) => sum + value, 0);
document.getElementById('getPrice').innerHTML = total;
}
.priceInput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
.priceOutput {
display: block;
border: 1px solid black;
padding: 10px;
width: 300px;
text-align: center;
margin-left: auto;
margin-right: auto;
}
<div class="priceInput">
<p>Part 1</p>
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="10">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="25">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="12">
</div>
<div class="priceInput">
<p>Part 2</p>
<label for="test4">test4</label>
<input type="radio" name="price2" id="test4" value="5">
<label for="test5">test5</label>
<input type="radio" name="price2" id="test5" value="7">
<label for="test6">test6</label>
<input type="radio" name="price2" id="test6" value="2">
</div>
<div class="priceInput">
<p>Part 3</p>
<label for="test7">test7</label>
<input type="radio" name="price3" id="test7" value="250">
<label for="test8">test8</label>
<input type="radio" name="price3" id="test8" value="720">
<label for="test9">test9</label>
<input type="radio" name="price3" id="test9" value="410">
</div>
<br>
<div class="priceOutput">
<button onclick="showPrice()">Show Price</button>
<p>Your Price is : <span id="getPrice">0<!--Here i want to get price1(value) + price2(value) + price3(value)--></span> $</p>
</div>
By looking at your code, it seems that you want to get the option the user selected out of the radio buttons and not all radio buttons (referring to the getElementsByName). To do so, you can go over the nodeList returned and see if any of the elements have the checked property.
for(let i = 0; i < priceOne.length; i++){
if(priceOne[i].checked) {
//Get value of the price selected with .value
let priceOneValue = priceOne[i].value;
}
}
After doing this for all your input types, you can sum them up.
JO_VA here is my own code. Can you check it? It's easier for my understanding.
I found just 1 problem and it is : when i remove from HTML input tag "checked" and i klikn only for 1 or 2 radio options, it show NaN in paragraph for price.
BTW sorry for my english (i ussually dont use english language)
function showPrice(){
var pricePlace = document.getElementById("getPrice");
getVal1();
getVal2();
getVal3();
var InputNumber = Number(inputVal1) + Number(inputVal2) + Number(inputVal3);
pricePlace.innerHTML = InputNumber;
}
var inputVal1;
function getVal1(){
var a = document.getElementById("test1");
var b = document.getElementById("test2");
var c = document.getElementById("test3");
if (c.checked) {
inputVal1 = c.value;
}
if (b.checked) {
inputVal1 = b.value;
}
if (a.checked) {
inputVal1 = a.value;
}
}
var inputVal2;
function getVal2(){
var a = document.getElementById("test4");
var b = document.getElementById("test5");
var c = document.getElementById("test6");
if (c.checked) {
inputVal2 = c.value;
}
if (b.checked) {
inputVal2 = b.value;
}
if (a.checked) {
inputVal2 = a.value;
}
}
var inputVal3;
function getVal3(){
var a = document.getElementById("test7");
var b = document.getElementById("test8");
var c = document.getElementById("test9");
if (c.checked) {
inputVal3 = c.value;
}
if (b.checked) {
inputVal3 = b.value;
}
if (a.checked) {
inputVal3 = a.value;
}
}
Or you can check it in https://codepen.io/soorta/pen/gqEGyQ
I have a slider that live-updates the value on a label tag to the right of it. What should I do to prevent it from "jumping" when the value goes from 1-digit value to 2-digits value? How can I give the label a fixed position so that it won't change the layout:
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<label id="label">0</label>
<input id="range" type="range" value=0 min=0 max=100>
Either add width: 20px;display: inline-block; to the label.
Or
Add a wrapper around both the elements and give them display: flex; align-items: center; style and width to the label.
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<div style="display: flex; align-items: center;">
<label id="label" style="width: 20px;">0</label>
<input id="range" type="range" value=0 min=0 max=100>
</div>
Option 1: Put label to right side of slider
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
label.innerHTML = this.value;
}
<input id="range" type="range" value=0 min=0 max=100>
<label id="label">0</label>
Option 2: Zero padding:
var range = document.getElementById('range');
range.addEventListener('input', rangeChange);
function rangeChange() {
var val = +(this.value);
if (10 > val) {
val = '00' + val;
} else if (100 > val) {
val = '0' + val;
}
label.innerHTML = val;
}
<label id="label">000</label>
<input id="range" type="range" value=0 min=0 max=100>
I've been researching for a few days methods of controlling UI with checkboxes and with the help of some members on Stack' I've come really quite far. But my balding doesn't quite stop yet. I've been trying to further tweak my code snippet, by including a numeric value alongside my UI controller. (This value will be of use later inside the web-java applet.)
For example, when a checkbox is checked var total is ammended from 0 to 30. If a Checkbox is unchecked the value returns to '0'.
(Main Build JS Fiddle),
(Checkbox Example).
The second fiddle allows the use of data attributes, however these will need to be injected into the HTML via, JS. As like before I have 'NO' access to the CSS or HTML source files.
(Original Post)
- This post is a follow on from another question asked here on stack, due to the nature of the question changing, and the comments getting fairly confusing I was asked to open a new thread.
Below I'll post two snippets, one is of the original build, built with the aid of user #acontell. The other is an example of the type of result I am after, built with the aid of, user #Rajesh. Link to (Example Source).
The Base Build
// Control UI...
(function(domElements, cbState) {
// Number increment
var total = 0 + ' mm';
document.getElementById('adjvar').value = total;
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// increment count...
var val = 30;
total += (+val * (checkBox.checked ? 1 : -1));
document.getElementById('adjvar').value = total + ' mm';
document.getElementsByClassName('adjvar').value = checkBox.checked ? val : 0 + ' mm';
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
}
domElements
.filter(function(el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function(el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
// inject style
function ctSe() {
var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.log(head)
console.log(style)
console.log(css)
};
ctSe();
.editoraccvar {
width: 300px;
background: #f0f;
padding: .5em;
}
.editoropt {
width: 300px;
background: #0f0;
padding: .5em;
}
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<!-- Secondary Division -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">First Floor</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Secondary Checkbox -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<input name="adjvar" id="adjvar" readonly>
The Example
(function() {
var total = 0;
function calculate(index) {
var el = document.getElementsByClassName('checkbox-input')[index];
var val = el.getAttribute("data-value");
total += (+val * (el.checked ? 1 : -1));
document.getElementById('pnvar').value = total;
document.getElementsByClassName('pnvar')[index].value = el.checked ? val : 0;
}
function registerEvents() {
var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function(cb, i) {
cb.addEventListener("click", function() {
calculate(i);
});
});
document.getElementById('pnvar').addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
})
}
window.addEventListener('load', function() {
registerEvents();
calculate(0)
})
})()
.editoropt {
font-family: Calibri, sans-serif;
width: 160px;
background: #f8f8ff;
padding: .5em;
border: solid 1px #ddd;
}
#checkboxopt {
float: left;
margin-right: 1em;
margin-top: 4px;
}
#checkboxopt1 {
float: left;
margin-right: 1em;
margin-top: 4px;
}
.pnvar {
width: 95%;
}
input:-moz-read-only {
/* For Firefox */
background-color: transparent;
border: none;
border-width: 0px;
}
input:read-only {
background-color: transparent;
border: none;
border-width: 0px;
}
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Default 80mm </span>
<input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" checked />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Add 30mm </span>
<input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true" />
<input type="hidden" name="opt2" id="opt2" value="true" />
</label>
</div>
<div class="editoropt">
<input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text">
<input name="adjvar" class="pnvar" id="adjvar" readonly value="0">
<input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">
</div>
As I mentioned in my previous post, I'm not a JS Whizz and I'm just finding my feet, however I am abitious to learn and further my knowledge. Any assistance would be greatly appreciated.
Note : All tags, classes and names, must remain the same for consistancy with another application.
I might be mistaken but I think that this two lines of code:
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
Could be avoided if you passed [true, false] as the initial states of the checkboxes:
([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);
I might be wrong, you might be doing something else or the state of the page could require that click, I don't know.
Going back to the issue, if you want to increase/decrease by 30 when the checkbox is checked/unchecked, you could do as follows:
Create a function that retrieves the value of the input an updates it with a quantity added to it. The value of the input is a string of the form 'x mm' so a bit of tinkering is necessary to get the integer part of the value.
function updateInputValue(n) {
var actual = +document.getElementById('adjvar').value.split(' mm')[0] || 0;
document.getElementById('adjvar').value = (actual + n) + ' mm';
}
Inside toggleElement call this function in order to update the input value.
var increment = isShown ? 30 : -30;
updateInputValue(initialShow === undefined ? increment : +initialShow * 30);
It gets a bit complicated because you have to control the initial state of the inputs, but it's not that hard: if it's the initial state, initialShow is different from undefined so we transform the value (it's a boolean) into a number a multiply it by 30 (when it's checked, it'd be 1 * 30, when it's unchecked it'd be 0 * 30). When it's not the initial state, we increment/decrement depending on whether it's checked or not.
And here's the fiddle (I also commented out the part that clicked the checkbox). Hope it helps.
I have a list of textboxes inside a parent div, say 'parentDom'. I need to attach a data attribute 'list' to each of these textboxes which has the list of values of all the textboxes under parentDom, except for itself.
So far, I have this
$('input').each(function(index, item) {
var list = _.pluck(
_.reject(
$('input'),
function(obj) {
return $(obj).data('id') == $(item).attr('id')
}
),
'name');
$(item).data('list', list);
});
Am using underscore.js. Is this the right way?
One way of doing this (assuming I'm interpreting the question correctly) is:
// getting a reference to the relevant <input /> elements:
var inputs = $('#parentDom input');
// iterating over each of those <input /> elements, with attr():
inputs.attr('data-value', function() {
// creating a reference to the current <input /> over which we're iterating:
var cur = this;
return inputs.filter(function() {
// filtering the jQuery collection to remove the current <input />
return this !== cur;
}).map(function() {
// converting the (string) value to a number, using the
// unary plus operator:
return +this.value;
// creating an array of the values
}).get().reduce(function(a, b) {
// reducing the array of values to a single value,
// by summing the previous and current values together:
return a + b;
});
});
// inserting a <span> after the <input /> elements,
// just to show the result:
inputs.after(function() {
return '<span>' + this.dataset.value + '</span>';
});
input {
display: inline-block;
float: left;
clear: left;
margin: 0 0 0.4em 0;
}
span {
float: left;
margin-left: 0.5em;
}
span::before {
content: '(data-value: ';
}
span::after {
content: ').';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDom">
<input type="text" value="1" />
<input type="text" value="2" />
<input type="text" value="3" />
<input type="text" value="4" />
<input type="text" value="5" />
<input type="text" value="6" />
<input type="text" value="7" />
</div>
A somewhat simpler approach, however, would be:
// getting a reference to the relevant <input /> elements:
var inputs = $('#parentDom input'),
// finding the total of *all* the <input /> elements:
totalValue = inputs.map(function() {
return +this.value;
}).get().reduce(function(a, b) {
return a + b;
});
// iterating over the <input /> elements with attr():
inputs.attr('data-value', function() {
// setting the data-value attribute to the total value
// of all the <input /> elements minus the value of the
// current <input />:
return totalValue - (+this.value);
});
// inserting a <span> after the <input /> elements,
// just to show the result:
inputs.after(function() {
return '<span>' + this.dataset.value + '</span>';
});
input {
display: inline-block;
float: left;
clear: left;
margin: 0 0 0.4em 0;
}
span {
float: left;
margin-left: 0.5em;
}
span::before {
content: '(data-value: ';
}
span::after {
content: ').';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDom">
<input type="text" value="1" />
<input type="text" value="2" />
<input type="text" value="3" />
<input type="text" value="4" />
<input type="text" value="5" />
<input type="text" value="6" />
<input type="text" value="7" />
</div>
References:
JavaScript:
Array.prototype.reduce().
jQuery:
attr().
get().
map().