I have a JavaScript variable:
var setClickTime = "2000";
I would like to give the user a choice of 2000 or 4000 based on their preference by clicking a button.
What is the best way to allow the user to change this variable? I have considered having two buttons one of which will have the class active when clicked. That would require me to set up an if / else statement to change the variable based on which button is active. But I am new to this and I do not know the best approach.
Just give your buttons IDs and bind listeners.
Say, you have two buttons id="setTime2000" and id="setTime4000", then you just need:
HTML Code:
<div>
<button id="setTime2000">Set time as 2000</button>
<button id="setTime4000">Set time as 4000</button>
</div>
JS Code:
$(document).ready() {
var mTime = 2000; // set the default value of time
$("#setTime2000").click(function () {
mTime = 2000;
}
$("#setTime4000").click(function () {
mTime = 4000;
}
// ... do something with the variable set
}
Do you just want a button event listener to change it:
<button id="changeBtn">4000</button>
JS
var setClickTime = "2000";
$("#changeBtn").click(function() {
setClickTime = "4000";
})
First, you have a JavaScript variable, it has nothing to do with jQuery.
Then, if you want something easy, without dependencies. Here a simple example:
var myValue = 2000;
updateOutput();
a.addEventListener('click', function() {
myValue = 2000;
updateOutput()
});
b.addEventListener('click', function() {
myValue = 4000;
updateOutput()
});
function updateOutput() {
output.value = myValue;
}
<button id="a">2000</button>
<button id="b">4000</button>
<input readonly id="output">
A generic answer in pure javascript.
<button class='setTime'>
2000
</button>
<button class='setTime'>
4000
</button>
Pure Javascript:
var setClickTime = "";
var buttons = document.getElementsByClassName('setTime')
for (i = 0; i < buttons.length; i++) {
this.onclick = function setTime(event) {
setClickTime = event.target.innerHTML;
alert(setClickTime);
}
}
fiddle: https://jsfiddle.net/b1vy8ahp/
You can define multiple radio buttons for more options ( with same name attribute to group them ) and then just delegate or bind a change event on that group of radios buttons to get the selected value.
<input type="radio" name="test" value="2000">2000
<input type="radio" name="test" value="4000">4000
<script>
var setClickTime;
$('input:radio[name=test]').on('change',function()
{
setClickTime = this.value;
});
</script>
Example : https://jsfiddle.net/DinoMyte/71hgeqnb/1/
Related
I need create button which count click but make every time new string. I have that function with scope which make count every time when I click, but I cannot understand, why in HTML it every time count zero, should be like this:
(Verticaly every click make new string with updated count)
1
2
3
4
...
<form action="#">
<input type="button" value="Count" onclick="add_count()">
</form>
function add_count() {
let integer = (function () {
let counter = 0;
return function() {return counter++;};
}());
let tag = document. createElement("p");
let text;
text = document. createTextNode(integer());
tag. appendChild(text);
let element = document. getElementsByTagName("body")[0];
element. appendChild(tag)};
You just need to move the counter initialization outside of the function scope
I've tweaked your code a bit.
Note: try not using inline event listeners, instead use event listeners in JavaScript file
let counter = 0;
const button = document.querySelector('input');
function add_count() {
let integer = (() => counter++);
const tag = document.createElement("p");
const text = document.createTextNode(integer());
tag.appendChild(text);
const element = document.body
element.appendChild(tag)
};
button.addEventListener('click', add_count)
<form action="#">
<input type="button" value="Count">
</form>
I am trying to create a slideshow but the addEventListener is not working !!
i am beginner in js world and want to get better by projects but this simple project has stumped me.
const nextBtn = document.querySelector(".next-btn");
const prevBtn = document.querySelector(".prev-btn");
const slides = document.querySelectorAll(".slide");
const slider = document.querySelector(".slider");
const slideIcons = document.querySelectorAll(".slide-icon");
// selecting total number of slides
const numberOfSlides = slides.length;
// whatever
const slideNumber = 0;
// manual functionality
// next-btn
nextBtn.addEventListener("click" ,() => {
slides.forEach(slide =>{
slide.classList.remove("actve");
});
slideIcons.forEach((slideIcon) => {
slideIcon.classList.remove("active");
});
})
I don't got the whole situation but as I see your need to add event Listener to your slider so am gonna give you ex about range slider event handler
// 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");
}
}
now 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");
}
});
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)
Try giving your html elements an id and then use getElementById instead of querySelector
I have a form that has several radio groups. There is one particular radio group that I want the user to be able to reset without resetting the entire form. I created a button whose value is Reset Participation Levels. Here is the function for the click event of that button:
<script>
function ParticipationReset(){
document.getElementById('SponsorshipParticipaton_0').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_1').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_2').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_3').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_4').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_5').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_6').removeAttribute('disabled');
document.getElementById('ExhibitorParticipaton_0').removeAttribute('disabled');
document.getElementById('ExhibitorParticipaton_1').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_0').checked = false;
document.getElementById('SponsorshipParticipaton_1').checked = false;
document.getElementById('SponsorshipParticipaton_2').checked = false;
document.getElementById('SponsorshipParticipaton_3').checked = false;
document.getElementById('SponsorshipParticipaton_4').checked = false;
document.getElementById('SponsorshipParticipaton_5').checked = false;
document.getElementById('SponsorshipParticipaton_6').checked = false;
document.getElementById('ExhibitorParticipaton_0').checked = false;
document.getElementById('ExhibitorParticipaton_1').checked = false;
}
</script>
However, when I click the button, all radio buttons in the form are reset even if they are not specified in the function. The link to the page is www.pfacmeeting.org/2016/exhibitorform.htm.
Any advice would be appreciated. Thank you
cdr6545
this is happening because the button is set as "reset" , for a particular reset, please change the line to:
<input type="button" name="ResetSponsor" id="ResetSponsor" value="Reset Sponsorship Participation" onclick="javascript:SponsorshipReset(this);" />
type="button"
You can reset all of the radio buttons in a group with a simple for loop like this:
var elements = document.getElementsByName("SponsorshipParticipation");
for(var i = 0; i < elements.length; i++) {
elements[i].removeAttribute("disabled");
elements[i].checked = false;
}
Or if you want to reset all radio button groups with a name ending in "Participation", you could change the first line to this:
var elements = document.querySelectorAll("input[name$='Participation']");
Here is an example of how you could implement the code I provided above:
HTML
<input type="button" value="Reset" onclick="resetParticipation()" />
JavaScript
function resetParticipation() {
var elements = document.querySelectorAll("input[name$='Participation']");
for(var i = 0; i < elements.length; i++) {
elements[i].removeAttribute("disabled");
elements[i].checked = false;
}
}
I have the following code
$(document).ready(function () {
$('#big_1').change(function () {
var bigAmt = document.getElementById("big_1").value
+ document.getElementById("big_2").value
+ document.getElementById("big_3").value
+ document.getElementById("big_4").value
+ document.getElementById("big_5").value
+ document.getElementById("big_6").value
+ document.getElementById("big_7").value
+ document.getElementById("big_8").value
+ document.getElementById("big_9").value
+ document.getElementById("big_10").value;
var elem = document.getElementById("totalBig");
elem.value = bigAmt;
});
});
I actually wanted to add the value of big_1 to big_10 on input text value change of "big_1 to big_10" either 1 of the textfield change its value, this should be invoke.
as of now i only run on big_1 change event.
I get an javascript error by adding this way, I think the way I add them up is quite messy.
What should I do to change my code so I can sum up
big_1 to big_10 textfield value, and on change of big_1 to big_10(any of them), it will invoke this and change span id="totalBig" to the value of their sum (big_1 add until big_10)
Below is my edited extra code:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_1" id="big_1" size="6">
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_2" id="big_2" size="6">
all the way until big_10
I wanna on change value of any of this big_Identifier(1-10), it will sum it up and change my
<div class="well">
Total Big: <span id="totalbig">0</span> </span>
</div>
I tried the
<script type="text/javascript">
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
$('.big').change(function() {
var bigAmt = "";
$('.big').each(function () {
bigAmt += $(this).val();
})
var elem = document.getElementById("totalBig");
alert(bigAmt);
elem.value = bigAmt;
});
});
</script>
It doesn't run any alert when any of the big_ value was changed.
It would be much better if you added a big class to every single <input id="big_NUMBER">. Then you could do this:
$(document).ready(function() {
$('.big').change(function() {
var bigAmt = 0;
$('.big').each(function () {
bigAmt += Number($(this).val());
})
$("#totalBig").val(bigAmt);
});
});
That's much cleaner and easier to understand than what you had.
In order for this to work, you'll need to add a class to all your inputs:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control big" name="big_2" id="big_2" size="6"><!-- Notice the big class-->
This is the best way to group all your inputs. They are all related, so they should share a classes. You should not be calling multiple ids for functionality that's so similar.
If you are using jquery, use it properly, it'll make your life a lot easier.
This will work for you in your case exactly
$(document).ready(function() {
$('[id^="big"').change(function(){
var total = (+$('#totalBig').val());
var currentVal = (+$(this).val());
total += currentVal;
$('#totalBig').val(total)
})
});
DEMO
Add class="bigs" to all inputs and then try this:
$(document).ready(function () {
var intTotalBig;
$('.bigs').change(function () {
intTotalBig = 0;
$('.bigs').each(function(){
$thisVal = $(this).val();
if ($.isNumeric($thisVal)){
intTotalBig += parseInt($thisVal, 10);
}
});
$("#totalBig").val(intTotalBig);
});
});
This code check all inputs on every change and sum all of them that has a number value and ignore empty or no number values.
Check JSFiddle Demo
You monitor the change event on all the input type text as follows:
$('input:text').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
Or...
If you want add the monitor to any selected text boxes then you will have to add any css class to those selected text boxes and then monitor those text boxes through class as follows:
$('.yourclass').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
this change event will fire when you lose focus from the text box after changing the text....
but if you want with loosing the focus (means if you want to update the count while typing) then you should use keyup event as stated in this answer.
$(document).ready(function() {
$('#big_1').change(function() {
var divArray = ["big_1","big_2","big_3","big_4","big_5","big_6","big_7","big_8","big_9","big_9","big_10"];
var bigAmt = 0;
for(var i = 0, n = divArray.length;i<n;i++)
{
bigAmt += parseInt($("#" + divArray[i]).val(),10);
}
$("#totalBig").val(bigAmt);
});
});
Try the above, it should do what you're looking for. You'll probably want to use parseInt as well incase the input isn't of "number" type.
*edit, forgot the # for the id.
*edit, removed comment about considering using jquery functions because people are really sensitive.
I want a div that shows your input, but for example * 2.
I also want it to happen as you type. So it has to be 'live'.
I found a lot of 'on keyup' jquery functions but I need to change the 'variable' that is typed in the input field.
So for example:
<input id="input" /> (types 4)
<div class="showinputhere"> (shows 8) </div>
How do I do this, it has to happen immediately when you type.
Use this
$(document).ready(function()
$('input').keyup(function(){
$('.showinputhere').html(parseInt($(this).val(),10) *2);
});
});
JSFiddle -> http://jsfiddle.net/gLExt/
try the following code:
<script>
function calVal(inputVal){
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
div.innerHTML = inputVal * 2 == 0 ? "" : inputVal * 2;
}
</script>
And call the function "onkeyup" event of input like this:
<input id="input" onkeyup="calVal(this.value);"/>
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("change", function() {
div.innerHTML = this.value * 2;
})
That's untested, but might work.
Here's an edited version using keyup, because I've been informed that change does not auto-update.
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("keyup", function() {
div.innerHTML = this.value * 2;
})