JavaScript fetching multiple known element IDs - javascript

I'm learning JS by making a character sheet (rpg), I got a form set up like this
<fieldset id="char-int">
<label for="int">INT</label>
<input id="int" name="int" placeholder="40" type="number" min="0" max="100">
<input id="int-hard" name="int-hard" placeholder="20" type="number" min="0" max="100">
<input id="int-extr" name="int-extr" placeholder="6" type="number" min="0" max="100">
</fieldset>
I need to change the value in int-hard and int-extr with simple rounded down division.
window.onchange = changevalue;
function changevalue() {
var hardRoll = document.getElementById("int").value / 2;
var extrRoll = document.getElementById("int").value / 5;
var setStat = document.getElementById("str-hard").value = Math.floor(hardRoll);
var setStat = document.getElementById("str-extr").value = Math.floor(extrRoll);
This works, but there must be a smarter way to do this as I got multiple IDs I want to do the same stuff to like STR, DEX etc..

You can remove the ids from your inputs and work within the context of your fieldset, like this:
<fieldset id="char-int">
<label>
INT
<input name="int" placeholder="40" type="number" min="0" max="100">
</label>
<input name="int-hard" placeholder="20" type="number" min="0" max="100">
<input name="int-extr" placeholder="6" type="number" min="0" max="100">
</fieldset>
function changevalue() {
var fieldset = document.getElementById("char-int");
var intField = fieldset.querySelector('["name=int"]');
var intHardField = fieldset.querySelector('["name=int-hard"]');
var intExtrField = fieldset.querySelector('["name=int-extr"]');
// ...
}
(Note that I also moved your name="int" field into the label so we don't have to use an id to link them.)
querySelector finds the first element within the element you call it on that matches the given CSS selector. (There's also querySelectorAll, which finds a list of all matching elements.)
Depending on how much you can parameterize the actual logic of the changevalue function, you could change the names to not have int- in them (or add classes), and then pass in the id of the fieldset (or the fieldset instance itself).
<fieldset id="char-int">
<label>
INT
<input id="int-main" name="main" placeholder="40" type="number" min="0" max="100">
</label>
<input name="hard" placeholder="20" type="number" min="0" max="100">
<input name="extr" placeholder="6" type="number" min="0" max="100">
</fieldset>
function changevalue(fieldSetId) {
var fieldset = document.getElementById(fieldSetId);
var mainField = fieldset.querySelector('["name=main"]');
var hardField = fieldset.querySelector('["name=hard"]');
var extrField = fieldset.querySelector('["name=extr"]');
// ...
}
QS and QSA are supported by all modern browsers, and also IE8.

I got multiple IDs I want to do the same stuff ...
When you here such a phrase, it can be a sign that you need to use classes. They are used exactly for this: to denote group of similar elements.
So what you should do is to add the same class to all elements, then select all necessary elements, and then use for loop to process all of them.
For example, HTML:
<input class="int" name="int" placeholder="40" type="number" min="0" max="100">
<input class="int-hard" name="int-hard" placeholder="20" type="number" min="0" max="100">
<input class="int-extr" name="int-extr" placeholder="6" type="number" min="0" max="100">
and then javascript:
var int = document.querySelectorAll('.int');
for (var i = 0; i < int; i++) {
var hardRoll = int[i].value / 2;
var extrRoll = int[i].value / 5;
}

Try this solution:
// Your inputs, selected by ID
var inputs = document.querySelectorAll("#int-hard, #int-extr");
// Apply onchange to selected input fields
for(var i = 0, length = inputs.length; i < length; i++) {
inputs[i].onchange = function() {
this.value = Math.floor(this.value);
};
}
And please don't use window.onchange as this fires off to every change in your document.

Related

How to display input value on page in Javascript?

How to display input value on the website? I already tried to display it but when I change the value of the input, the display is still the same.
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
What you did puts the value of the input in the paragraphe on load. Plus you need an EventListener in order to track the input changes, like so:
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
rangeInput.addEventListener("input", ()=>{
valueInp.innerHTML = rangeInput.value;
})
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
rangeInput.addEventListener("input", () => {
valueInp.textContent = rangeInput.value;
});
valueInp.textContent = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>```
Provided that the <p> element for the value will always be following directly after your range element then the following script will take care of any number of range/value combinations:
document.querySelectorAll(".range")
.forEach(r=>r.addEventListener("input",update(r)));
function update(r){
const ur= ()=>r.nextElementSibling.textContent=r.value;
ur();
return ur;
}
<input type="range" min="1" max="100" value="40" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="20" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="30" step="1" class="range"/>
<p></p>
Try this :
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
range.addEventListener("change",()=>{
valueInp.innerHTML = rangeInput.value;
})
valueInp.innerHTML = rangeInput.value;
addEventListener here will be executed whenever value inside input tag is changed .
You need to wire-up an event-listener on the <input/> which then updates the <p class="value"> in the event-handler.
You can only wire-up event-handlers after DOMContentLoaded btw.
There are two main events you can listen to:
Use the 'input' event to respond to every change-in-value, even while the <input> element has focus.
Use the 'change' event to only respond to changes when the user has stopped interacting with the input.
BTW, you should use an <output> element instead of <p> for showing "output" values.
You should use id to select specific elements instead of .className selectors because class="" is not unique.
Never use innerHTML for showing text as it opens you up to XSS attacks.
For <output> you can set HTMLOutputElement.value.
For all other elements, use textContent.
Or innerText.
Like so:
window.addEventListener( 'DOMContentLoaded', onDomLoaded );
function onDomLoaded() {
const rangeInput = document.getElementById('myRangeInput');
const output = document.getElementById('myOutput');
// Show initial value immediately:
output.textContent = rangeInput.value;
// 'input' is the name of the event-type, not the <input> element name.
// you can also use 'change' instead.
rangeInput.addEventListener( 'input', e => {
output.textContent = rangeInput.value;
} );
}
<input id="myRangeInput" type="range" min="1" max="100" value="1" step="1" class="range"/>
<output id="myOutput" for="myRangeInput"></output>
If you want something really succinct, then just update the <output> dire use a named <output> the oninput="" attribute, like so:
<input id="myRangeInput" type="range" min="1" max="100" value="1" step="1" oninput="document.getElementById('myOutput').value = this.value;" />
<output id="myOutput" for="myRangeInput"></output>

Focus/unfocus an input on range slider handler's use

I have a form where the inputs values are controlled by range sliders. There's a calculation every time there's a new entry on each input which operates on focusout.
Though, the calculation doesn't work when only the range sliders are used. Is there a way to focus the inputs while using the range sliders? I can't change the way of calculation, because, it's on all the inputs. So, it has to be this way.
My form is bigger, but, here's an example of what I have:
<label class="va1">Option a price 1:<input id="a1" type="number"/></label>
<input type="range" id="slider-a1" min="0" max="100" step="1" value="0"><br>
<label class="va2">Option a price 2:<input id="a2" type="number"/></label>
<input type="range" id="slider-a2" min="0" max="100" step="1" value="0"><br>
<label>Result:</label><input id="a5" type="text" name="total_amt"/>
And here's the JS:
var opt_1 = document.getElementById("slider-a1");
opt_1.oninput = function() {
document.getElementById("a1").value = opt_1.value;}
var opt_2 = document.getElementById("slider-a2");
opt_2.oninput = function() {
document.getElementById("a2").value = opt_2.value;}
calculate = function(){
var optiona1, optiona2, resultss;
optiona1 = Number(document.getElementById("a1").value);
optiona2 = Number(document.getElementById("a2").value);
resultss = parseInt(optiona1)+parseInt(optiona2);
document.getElementById('a5').value = resultss;}
$('input[type=number]').on('focusout', calculate);

getElementsByName instead of getElementById

I have a computation fare using the getElementById.innerHTML the total fare showing using <h5 id="totalFare"></h5> but instead if getElementByID i want to parse in getElementsByName by using a <input type="number" name="totalFare" readonly /> i'm searching a lot page to find out the answer, below is my codes. i hope you can help me.
<input type="number" id="adults" min="0" onkeyup="calculate()" name="booking[adults]" class="validate" value="0" required>
<input type="number" id="children" min="0" onkeyup="calculate()" name="booking[children]" class="validate" value="0" required>
<input type="number" id="senior" min="0" onkeyup="calculate()" name="booking[senior]" class="validate" value="0" required>
<script type="text/javascript">
function calculate(){
var adults = document.getElementById("adults").value;
var children = document.getElementById("children").value;
var senior = document.getElementById("senior").value;
var Fare = document.getElementById("hideFare").value;
var values = fare(adults, children, senior, Fare);
console.log(values)
document.getElementById("totalFare").innerHTML = values.totalFare;
}
function fare(x, y, z, a) {
var res = {};
res.totalFare = (( x * a) + (y * (a *.80)) + (z * (a *.80)))
return res
}
</script>
Use getElementsByName like below.
console.log(document.getElementsByName("test")[0].value);
<input type="text" name="test" id="testing" value="This is a value" />
The document.getElementsByName("test") gives you something like an array (called a collection of elements since there could be multiple elements with the same name), so the [0] is there to get the first index which is the value you wanted. Look at the link below for more information.
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

How to swap values by changing one of them via javascript?

There are three fields with numbers from 1 to 3. I am trying to make it so if a person uses only the arrows there should always be one "1", one "2", and one "3". Why is it not always working and how could I make it work?
jQuery(document).ready(function($) {
var prevNumber;
$(".numbers").focus(function() {
prevNumber = $(this).val();
}).change(function() {
curNumber = $(this).val();
$('.numbers[value="' + curNumber + '"]:not(:focus)').first().val(prevNumber);
prevNumber = curNumber;
});
});
<input type="number" value="1" min="1" max="3" step="1" class="numbers" />
<input type="number" value="2" min="1" max="3" step="1" class="numbers" />
<input type="number" value="3" min="1" max="3" step="1" class="numbers" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Here is a jsfiddle.
Why that approach doesn't work
The value attribute is not connected to the value of the input. I know that sound surprising. :-) The value attribute is the default value of the input. It doesn't change (unless you use setAttribute("value", x); or .defaultValue = x; to change it).
Your selector uses the attribute:
$('.numbers[value="' + curNumber + '"]')...
So it'll work on inputs whose value hasn't been changed by the user, but will fail once they have, selecting the wrong input.
How you could fix it
You could change the default value as well as the value by setting both defaultValue and value (being sure to update the defaultValue on the one that changed, too), like this (see comments):
jQuery(document).ready(function($) {
var prevNumber;
$(".numbers").focus(function() {
prevNumber = $(this).val();
}).change(function() {
// Get the element wrapper
var $this = $(this);
// Get the current value
var curNumber = $this.val();
// Make sure the default value on this element is updated
this.defaultValue = curNumber;
// Update both the value and default value on the other
// input that used to have this number
$('.numbers[value="' + curNumber + '"]:not(:focus)').first().val(prevNumber).prop("defaultValue", prevNumber);
prevNumber = curNumber;
});
});
<input type="number" value="1" min="1" max="3" step="1" class="numbers" />
<input type="number" value="2" min="1" max="3" step="1" class="numbers" />
<input type="number" value="3" min="1" max="3" step="1" class="numbers" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
What I'd do instead (maybe -- your approach is growing on me)
I think I'd approach it without trying to remember state, e.g., just in the change: Get the number of the one that changed, then assign any other numbers to its siblings. See the comments:
var numbers = $(".numbers").map(function() { return this.value; }).get();
jQuery(document).ready(function($) {
$(".numbers").change(function() {
// Get a wrapper for this input
var $this = $(this);
// Get this number
var thisNumber = $this.val();
// Get the unused numbers
var unused = numbers.filter(function(num) { return num != thisNumber; });
// Assign them to the siblings, in order
$this.siblings().val(function(index) {
return unused[index];
});
});
});
<input type="number" value="1" min="1" max="3" step="1" class="numbers" />
<input type="number" value="2" min="1" max="3" step="1" class="numbers" />
<input type="number" value="3" min="1" max="3" step="1" class="numbers" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I kept that general, rather than assuming the values would only be 1, 2, and 3 (and rather than assuming there'd only be three numbers).
The problem in your code is that the "value" attribute contains the initial value for the input. When you use the following selector:
$('.numbers[value="' + curNumber + '"]:not(:focus)')
you are selecting the element that initially had the given value, and not has this value now.
Try this selector instead, and all will work fine:
$('.numbers:not(:focus)').filter(function(index, element){
return $(element).val() == curNumber;
})
Here is a jsfiddle. ;)
I'd like to propose you a more elaborate solution that might help you as your application grows: you should store the JS value apart from the <input /> controlling it (this way, adding multiple <input>s or modifying the value from your code becomes easier. The most important thing is that you should have a single trusted data storage independent from the DOM that is always in a valid state (in this case: without duplicates).
Given your problem (the values should be unique and only swaps should be possible), it's easier to handle it as a pure JS problem (and do not try to do everything in jQuery - though I agree it's a great lib, it's not necessarily the best tool for everything).
Here is my commented solution:
jQuery(document).ready(function($) {
// This array the current values of the inputs
var numbers = [1, 2, 3];
// numbers should not be modified directly but trough
// setNumber: this function ensures that numbers is ALWAYS
// a swap of the original value ([1, 2, 3]).
// When a value is set, this function returns the previous
// index of the value
function setNumber(index, newVal) {
// find other index
var prevIndex = numbers.indexOf(newVal);
if (prevIndex < 0) {
alert('Invalid value, please enter 1, 2 or 3');
}
// swap
numbers[prevIndex] = numbers[index];
numbers[index] = newVal;
return prevIndex;
}
// This function updates the inputs to ensure
// that their displayed value match the one stored in numbers
function updateNumbersView() {
$(".numbers").each(function(idx, elem) {
elem = $(elem);
if (parseInt(elem.val(), 10) !== numbers[idx]) {
elem.val(numbers[idx]);
}
});
}
$(".numbers").change(function() {
var self = $(this);
var curNumber = parseInt(self.val(), 10);
var curIndex = $(".numbers").index(self);
if (curNumber === numbers[curIndex]) {
return false; // no change
}
// update model:
var changedIndex = setNumber(curIndex, curNumber);
// updateView:
$('.numbers').eq(changedIndex).val(numbers[changedIndex]);
// or to be more generic (ie. multiple inputs for the same value):
// updateNumbersView();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="1" min="1" max="3" step="1" class="numbers" />
<input type="number" value="2" min="1" max="3" step="1" class="numbers" />
<input type="number" value="3" min="1" max="3" step="1" class="numbers" />
I would solve this by adding another property to each node.
jQuery(document).ready(function($) {
var $numbers = $('.numbers'),
off = false;
$numbers.each(function () {
this.prev = this.value;
});
$numbers.change(function () {
var source = this;
if (off) return; // this algorithm is already running
off = true;
$numbers.each(function () {
if (this !== source && this.value === source.value) { // if conflict
this.prev = this.value = source.prev; // swap with old value
}
});
this.prev = this.value; // update for next time
off = false; // re-enable
});
});
<input type="number" value="1" min="1" max="3" step="1" class="numbers" />
<input type="number" value="2" min="1" max="3" step="1" class="numbers" />
<input type="number" value="3" min="1" max="3" step="1" class="numbers" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Jquery getting values of slider inside .each loop

I have 3 sliders (they are dynamic, so I need to loop through them).
I have a jsFiddle here: http://jsfiddle.net/mtait/R5czJ/
HTML is:
<label for="slider1">item 1</label>
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0">
<label for="slider2">item 2</label>
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0">
<label for="slider3">item 3</label>
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0">
I am trying to loop through them, and create a JSON string:
function slide() {
var ExtraPrices = [20.00,30.00,50.00];
var ExtraIDs = [1,2,3];
var count = 0;
var arr = [];
$('.mtslide').each(function () {
var obj = {
id: ExtraIDs[count],
price: ExtraPrices[count],
number: $(this).slider("option", "value")
};
arr.push(obj);
count += 1;
});
alert(JSON.stringify(arr));
}
However, "number" or the value of the sliders, is always null:
How do I get the correct value of each slider, within my .each loop above?
thank you,
Mark
jQuery's each function actually gives you two variable: index and Element
http://api.jquery.com/each/
Assuming you want the value of each element you want something like this:
$('.mtslide').each(function (index, Element) {
var obj = {
id: ExtraIDs[index],
price: ExtraPrices[index],
number: $(Element).val()
};
arr.push(obj);
});
Keeping a separate array for price and id can be error prone. You should consider specifying additional values on an html element with data attribute.
http://html5doctor.com/html5-custom-data-attributes/
http://api.jquery.com/data/
Something like this:
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0" data-price="20.00" data-id="1">
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0" data-price="30.00" data-id="2">
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0" data-price="50.00" data-id="3">
Then you can call them more specifically to the element:
$('.mtslide').each(function (index, Element) {
var obj = {
id: $(Element).data("price"),
price: $(Element).data("price"),
number: $(Element).val()
};
arr.push(obj);
});
The complete fiddle:
http://jsfiddle.net/Wwwtv/2/

Categories