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;
})
Related
In a HTML website I have a textarea created like this:
<textarea id = "myTextArea" rows = "30" cols = "80"></textarea>
I would like after something is written in the text area, for that text to be sent to a variable in javascript.
I have tried doing this, but it did not work:
var x = document.getElementById("myTextArea").value;
The console.log(x); gives back nothing, not null, just empty space. However, if I log out console.log(document.getElementById("myTextArea").value) then I get the text that I have written in my textarea.
Why does var x = document.getElementById("myTextArea").value; not work?
My Javascript:
<script>
var x = document.getElementById("myTextArea").value;
const regex = /([a-z]+)/;
const match = regex.exec(x);
var intervalID = window.setInterval(myCallback, 500); <!-- Calls every 5s -->
function myCallback() {
if(match){
const name = match[1];
console.log(name);
}
else{
console.log('no match');
console.log(match);
}
}
To achieve this, you can register an event listener on your textarea:
var textArea = document.getElementById('myTextArea');
textArea.addEventListener('input', function(event){
console.log(event.target.value);
});
The listener listens for any input events on your textara and logs the value of your textarea as the value changes.
Here's a live demo for your quick reference.
You will need to use onkeyup and onchange for this. The onchange will prevent context-menu pasting, and the onkeyup will fire for every keystroke.
See my answer on How to impose maxlength on textArea for a code sample.
In my example, the variable is the text variable. This variable is filled with the text of the text by clicking on the button.
Was it necessary?
var x = document.getElementById("myTextArea");
var button = document.querySelector("button");
var text = "";
button.onclick = function() {
text = x.value;
console.log(text);
}
#myTextArea {
width: 100%;
height: 100px;
}
<textarea id="myTextArea" rows="30" cols="80"></textarea>
<button>Check variable with text</button>
Second example using oninput event.
var x = document.getElementById("myTextArea");
var text = "";
x.oninput = function() {
text = this.value;
console.log(text);
}
#myTextArea {
width: 100%;
height: 100px;
}
<textarea id="myTextArea" rows="30" cols="80"></textarea>
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/
I'm trying to repeat a div, the number of times dependent on the number chosen in a number input field, but currently when the number input is changed the values are being multiplied. So if you go from 2 to 3 it repeats the div 6 times instead of just 3. How can I reset the loop so it's using only the current number?
http://jsfiddle.net/deliciouslycheesy/6rb94mry/
$('#numRepeat').on('change keyup input', function () {
var el = $(".repeat-me").get(0);
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();
You need to remove the ones that were added before:
$('#numRepeat').bind('change keyup input', function () {
var el = $(".repeat-me").get(0);
$(".repeat-me:not(:first)").remove();
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="2"/>
<div class="repeat-me">REPEAT</div>
JSFiddle
I'm not sure why you're using three event change keyup input, just input event will detect changes inside input field, check the Updated fiddle.
I suggest to separate the model of repeated div from the result, i think that will make code more clear, and because you're using JQuery you can replace cloneNode() by clone().
Hope this helps.
$('#numRepeat').on('input', function () {
var el = $("#model-div .repeat-me");
var numRepeat = $(this).val();
$('#result-div').empty(); //Clear the result div
for(var i = 0 ; i < numRepeat ; i++)
{
$('#result-div').append( $(el).clone(true) );
}
})
#model-div{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="0"/>
<div id="model-div">
<div class="repeat-me">REPEAT</div>
</div>
<div id="result-div"></div>
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 have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element