I haven't found the right answer in any similar questions, so I hope someone may be able to point me in the right direction.
I have a simple script that updates some text based on a range slider selection. I have noticed this works in everything except Edge, and having little experience with Javascript I'm wondering how to fix it.
The HTML:
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value);" oninput="amount.value=rangeInput.value">
<p id="fruit_value">Pick a fruit</p>
The script:
<script type="text/javascript">
function updateTextInput() {
var fruit_range = Number(document.getElementById("pick_fruit").value);
var fruit_value = "";
if (
fruit_range === 1 ) {
fruit_value = "Apples";
}
else if (
fruit_range === 2 ) {
fruit_value = "Oranges";
}
else if (
fruit_range === 3 ) {
fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
Any help would be much appreciated.
Thanks in advance
Use the oninput event to trigger the function. An object that maps ints to strings cleans up the conditional a little...
const fruitMap = { 1:'Apples', 2:'Oranges', 3:'Pears' }
function updateTextInput() {
const v = +document.getElementById("pick_fruit").value
document.getElementById('fruit_value').innerHTML = fruitMap[v];
}
<input type="range" min="1" max="3" step="1" id="pick_fruit"
oninput="updateTextInput()">
<p id="fruit_value">Pick a fruit</p>
You don't need to add
var fruit_range = Number(document.getElementById("pick_fruit").value);
because you are already getting value from the your function (updateTextInput()), you need to provide an argument inside the function to get the onchange value. I tried to simplify the code you can test it.
<html>
<body>
<input type="range" min="1" max="3" step="1" id="pick_fruit" onchange="updateTextInput(this.value)">
<p id="fruit_value">Pick a fruit</p>
</body>
<script type="text/javascript">
var fruit_value = "";
function updateTextInput(value) {
if (value == 1 ) {
this.fruit_value = "Apples";
}
else if (value == 2 ) {
this.fruit_value = "Oranges";
}
else if (value == 3 ) {
this.fruit_value = "Pears";
}
document.getElementById('fruit_value').innerHTML = fruit_value;
}
</script>
</html>
Update
Also you need to change the conditions from "===" to "==" or change the min & max to number type, as in input tag the values are in string and "===" checks both and its type but as in condition you were comparing string type to number type it will always give a empty string .
Related
I am trying to make a simple calculator. You enter one number, you enter the second one, press PLUS and get alert with an answer. I need to show alert('no data') if you click on PLUS when input fields are not touched.
function num1() {
nm = document.getElementById('nsum1').value;
}
function num2() {
mn = document.getElementById('nsum2').value;
}
function plus() {
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
} else {
alert(sum);
}
}
<input onchange="num1()" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input onchange="num2()" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
So far I have tried if(sum == undefined)/if(sum == null)/if(sum == false)/if(isNaN(sum))/if(sum == "") and nothing seems to work.
If you haven't touched the input field and get the value, then the result would be ""
You need a condition like
if (nm == "" || mn == "") {
alert('no data');
}
And also you should do operation after validations. You are doing operation and then validating.
Fixed other issues aswell.
function plus() {
mn = document.getElementById('nsum2').value;
nm = document.getElementById('nsum1').value;
if (nm == "" || mn == "") {
alert('no data');
} else {
sum = +nm + +mn;
alert(sum);
}
}
<input id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<span onclick="plus()" id="sum">PLUS</span>
<input id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
You can do it much easier
function plus(num1, num2) {
alert(isNaN(num1) || isNaN(num2) ? 'No data' : num1 + num2);
}
function getNumber(id) {
return parseFloat(document.getElementById(id).value);
}
<input id="nsum1" type="number" placeholder="number" maxlength="6" />
<span onclick="plus(getNumber('nsum1'), getNumber('nsum2'))" id="sum">PLUS</span>
<input id="nsum2" type="number" placeholder="number" maxlength="6" />
I've made some changes to your code to make it more robust. See the inline comments for a description.
Declare variables
It is important to declare your variables, when you don't all the variables you are using will wind up in the global scope. When you Google this you will find many articles like this one: https://gist.github.com/hallettj/64478.
Prevent polluting the global scope. In a small website this may not be much of an issue but when working on larger project or with third party code, this is a must. The link above also explains this to some extend.
Use a button If you want something to be interactive, use an HTML element that was meant for it. The button element should be used, it has all sorts of accessibility features the span doesn't have. For instance, by default it will receive focus when navigating your website with the tab key.
Use descriptive variable names nm and mn may mean something to you now but in 6 months it will be a complete mystery. It also makes the code more readable and thus easier to maintain.
Attach event listeners in JS In general it is a bad idea to assign event listeners through the HTML attribute onXXX="". It is more error prone and a lot more time intensive when you want to change something.
// Wrap your code in a closure to prevent poluting the global scope.
(function() {
// Always declare your variables. These variables are no longer scoped to the window object but are no scoped to the function we're in.
var
valueA = null,
valueB = null;
/**
* To check if your input is a valid number requires a couple of checks.
* It is best to place these into their own method so you're other
* method is more readable.
*/
function isNumber(value) {
if (
// == null checks for undefined and null
value == null ||
value === '' ||
isNaN(value)
) {
return false;
}
return true;
}
function onChangeHandler(event) {
var
// Get the element that dispatched the event.
target = event.target;
// Check if the target has the class we've assigned to the inputs, of not you can ignore the event.
if (!target.classList.contains('js-input')) {
return;
}
// Based on the ID of the target, assign the value to one of the variables for the values.
switch(target.id) {
case 'nsum1':
valueA = parseFloat(target.value);
break;
case 'nsum2':
valueB = parseFloat(target.value);
break;
}
}
function onSumTriggerClicked(event) {
// Check if there are numbers to work with
if (
!isNumber(valueA) ||
!isNumber(valueB)
) {
// If not alert the user
alert('no data');
return;
}
sum = valueA + valueB;
alert(sum);
}
function init() {
var
// Get the calculator element.
calculator = document.getElementById('calculator'),
// Get the button to sum up the value.
sumButton = document.getElementById('sum-trigger');
// Add an event listener for the change event.
calculator.addEventListener('change', onChangeHandler);
// Add an event listener for the click event.
sumButton.addEventListener('click', onSumTriggerClicked);
}
// Call the init method.
init();
})();
<div id="calculator">
<input class="js-input" id="nsum1" name="numb" type="tel" placeholder="number" maxlength="6" />
<button type="button" id="sum-trigger" id="sum">PLUS</button>
<input class="js-input" id="nsum2" name="numb" type="tel" placeholder="number" maxlength="6" />
</div>
Try to track it via Inspector, maybe log the values of nm and mn before anything else and correct your condition accordingly(as the sample).
function plus() {
console.log(nm);
sum = +nm + +mn;
if (nm == null || mn == null) {
alert('no data');
}
It will most likely just be blank. So in this case you can modify your condition into:
if (nm === '' || mn === '') {...}
Hope it will help
Please use this as reference.
I've fixed your code.
if ( num1 === '' && num2 === '' ) {
alert('no data');
} else {
alert( parseInt(num1) + parseInt(num2) );
}
This code works fine on IE, but fails on Chrome.
Theory: When you click on the input, the input marks with an X or when you hit again the X is deleted (just like a checkbox) , when any of these conditions are met, the script should send the forms Y ( if X is checked) or N (if X is empty ).
HTML
Note: The values are generated dynamically using the data from a external database).
<input type="text" READONLY id="65535" class="chk" iffalse="N" iftrue="Y" value=""
onclick="fchkboxclick();" />
JavaScript
function fchkboxclick() {
object = window.event.srcElement;
if (object.id == '65535') {
if (object.value == 'X') {
activevalue = object.getAttribute("iffalse");
objet.value = '';
} else {
activevalue = object.getAttribute("iftrue");
object.value = 'X';
}
} else {
if (object.value == 'X') {
sendevent(object.id, 'check', object.getAttribute("iffalse"));
} else {
sendevent(object.id, 'check', object.getAttribute("iftrue"));
}
}
}
When I run this on any version of IE, the forms (sendevent function) receive the value from the attribute (Y or N) but in Chrome I just receive X.
Any help would be appreciated. Thanks.
if you use an onclick event in an element, far easier to do this
<input onclick="dosomething(this);" />
Then your code can do
function dosomething(element) {
// element is the element that was clicked
}
Ok, i done with this:
<html>
<body>
<input type="checkbox" name="chb[]" id="pepe" class='chk' iffalse="N" iftrue="Y" value="0" onchange="validate()" />
<br/> Value sent
<input type="text" id="1234" value="" />
<script type="text/javascript">
var inputcb = document.getElementById('1234');
function validate() {
if (document.getElementById('pepe').checked) {
inputcb.value = document.getElementById('pepe').getAttribute("iftrue");
} else {
inputcb.value = document.getElementById('pepe').getAttribute("iffalse");
}
}
</script>
</body>
</html>
I'm trying to get a range slider to work but I can't.
How do I add an event handler so when the user chooses a value my code reads that value. Right now its value is always 1.
I would like to do this using pure Javascript.
HTML:
<div id="slider">
<input class="bar" type="range" id="rangeinput" min="1" max="25" value="1" onchange="rangevalue.value=value"/>
<span class="highlight"></span>
<output id="rangevalue">1</output>
</div>
JAVASCRIPT:
var rangeInput = document.getElementById("rangeinput").value;
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
if (rangeInput > 0 && rangeInput < 5) {
alert("First");
} else {
alert("Second");
}
}
JSFIDDLE
Single Read
The problem is that you're only reading the value once (at startup), instead of reading it every time the event occurs:
// this stores the value at startup (which is why you're always getting 1)
var rangeInput = document.getElementById("rangeinput").value;
You should be reading the value in the handler instead:
function testtest(e) {
// read the value from the slider:
var value = document.getElementById("rangeinput").value;
// now compare:
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Or to rewrite your code:
var rangeInput = document.getElementById("rangeinput");
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
var value = rangeInput.value;
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Updating rangevalue
It also looks like you want to update the output element with the value of the range. What you're currently doing is referring to the element by id:
onchange="rangevalue.value=value"
However, as far as I know, this isn't standard behavior; you can't refer to elements by their id alone; you have to retrieve the element and then set the value via the DOM.
Might I suggest that you add a change listener via javascript:
rangeInput.addEventListener("change", function() {
document.getElementById("rangevalue").textContent = rangeInput.value;
}, false);
Of course, you'll have to update the code to use addEventListener or attachEvent depending on the browsers that you want to support; this is where JQuery really becomes helpful.
Use the mouseup event for that.
var rangeInput = document.getElementById("rangeinput");
rangeInput.addEventListener('mouseup', function() {
if (this.value > 0 && this.value < 5) {
alert("First");
} else{
alert("Second");
}
});
DEMO: http://jsfiddle.net/ZnYjY/1
You can also use the FORMs oninput method:
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" name="b" value="50" />100 +
<input type="number" name="a" value="10" /> =
<output name="result"></output>
</form>
This has an advantage over onclick/onmouseup because it handles the case where the slider is moved using the keyboard (tab to the input and use the arrow keys)
Use the oninput event.
HTML Codes:
<div id="slider">
<input class="bar" type="range" id="range-input" min="1" max="25" value="1"/>
<span class="highlight"></span>
<output id="range-value">1</output>
</div>
<button id="btn" type="submit">Submit</button>
Javascript scripts
(function() {
var rangeInput = document.getElementById("range-input")
var rangeValue = document.getElementById("range-value")
var button = document.getElementById("btn")
// Show alert message when button clicked
button.onclick = testTest
function testTest() {
let value = rangeInput.value
if(value > 0 && value < 5) {
alert("first")
return true
}
alert("second")
return false
}
// Print the range value to the output
rangeInput.oninput = rangeOutput
function rangeOutput() {
rangeValue.innerText = rangeInput.value
}
})()
Demo
UPDATE 2021
Another option is to use the input event handler i.e. eventTarget.addEventListener("input", alert("Hello World"), though this event handler is the same with oninput, the difference having we can use addEventListener
<script type="text/javascript">
function range()
{
//the simplest way i found
var p = document.getElementById('weight');
var res = document.getElementById('rangeval');
res.innerHTML=p.value+ " Lbs";
}
</script>
<label for="weight">Your weight in lbs:</label>
<input name="weight" type="range" id="weight" max="500" min="0" value="75" onChange="range()" onKeyUp="range()">
<span id="rangeval"></span>
i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...
Preamble: I'm more of a PHP/MySQL guy, just starting to dabble in javascript/jQuery, so please excuse this dumb newbie question. Couldn't figure it out from the Docs.
I have a form without a submit button. The goal is to allow the user to input values into several form fields and use jQuery to total them up on the bottom in a div. The form kinda looks like this but prettier:
<form>
Enter Value: <input class="addme" type="text" name="field1" size="1">
Enter Value: <input class="addme" type="text" name="field2" size="1">
Enter Value: <input class="addme" type="text" name="field3" size="1">
etc.....
<div>Result:<span id="result"></span></div>
</form>
Is it possible to add these up? And if so, can it be done anytime one of the input fields changes?
Thanks.
UPDATE:
Brian posted a cool collaborative sandbox so I edited the code to look more like what I have and it's here:
http://jsbin.com/orequ/
to edit go here:
http://jsbin.com/orequ/edit
Sticking this right after the </form> tag should do it:
<script>
function displayTotal() {
var sum = 0
var values = $('.addme').each(function(){
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#result').text(sum);
}
$('.addme').keyup(displayTotal);
</script>
Here's a demo: http://jsbin.com/iboqo (Editable via http://jsbin.com/iboqo/edit)
Any non numeric or blank values will be disregarded in the calculation (they'll be given a value of zero and hence not affect the sum).
function sumValues() {
var sum = 0;
$("input.addme").each(function(){
var $this = $(this);
var amount = parseInt($this.val(), 10);
sum += amount === "" || isNaN(amount)? 0 : amount;
});
$("#result").text(sum);
}
$(function() {
sumValues();
$("input.addme").keyup(function(){
sumValues();
});
});
Working Demo
(function(){
var context = $("form"), elements = $("input.addme", context);
function getSum(elements) {
var sum = 0;
$(elements, context).each( function() {
var v = parseInt(this.value);
v === parseInt(v,10) ? sum += v : sum = sum;
})
return sum;
}
$(elements).bind("keyup", function() {
$("#result").text( getSum(elements) );
});
})();
isolated scope and context, included dealing with non-integer values, function getSum should rather return a value than do something itself.
Try this:
$(".addme").bind("change",function(){
var _sum = 0;
$(".addme").each(function(i){
_sum += parseInt($(this).val());
});
$("#result").val(_sum);
});