applying onkeyup function simultaneously on multiple textboxes - javascript

Suppose I have a column of 1+7 text box. Name of the first box is mm1 and the other boxes are respectively dd1, dd2, ...., dd7. I want to write a javascript function so that all the values in the textboxes dd1, dd2,...,dd7 are multiplied by N if I put N in the first textbox namely mm1. I can write the javascript function , but how to make its effect in all boxes simultaneously? I have tried the following code. But it can effect only one box depending on the value of $i. If we can create a loop for $i taking values 1 to 7, then perhaps the problem will be solved. Any clue please.
<?php $i=3?>
<input type="text" size="1" id="mm1" name="mm1"
maxlength="2" onfocus="this.select()"
onkeyup="gft('dd<?php echo $i?>', 'mm1')"
>

Try this, use class to logically group elements...
$('.mult').each(function(i,v){
var tt = parseFloat($(this).val());
$(this).attr('data-val',$(this).val());
});
$('.myVal').on('keyup',function(e){
var t = $(this).val();
if(!t) t = 0;
$('.mult').each(function(i,v){
if(t>0){
var tt = parseFloat($(this).attr('data-val')) * t;
$(this).val(tt);
}
});
});
Find working fiddle here

function gft(x){
n = 5;
c = x * n;
textInputs[0].value = c;
textInputs[1].value = c;
textInputs[2].value = c;
}
var textInputs = document.querySelectorAll('input[type=text]');
//this eventlistener is made to listen for key movement on all text fields that are of type text
for(i=0;i<textInputs.length;i++){
textInputs[i].addEventListener('keyup',function(){
//gft will execute an equation whenever one of these fields change
//also, it will change all the values inside the textfield simultaneously
gft(this.value);
},false);
}

I made a JSFiddle using only JavaScript (no jQuery):
HTML
<input type="number" onkeyup="multiply(this)"/>
<input type="number" value="1" class="multiply-this"/>
<input type="number" value="2" class="multiply-this"/>
<input type="number" value="3" class="multiply-this"/>
<input type="number" value="4" class="multiply-this"/>
<input type="number" value="5" class="multiply-this"/>
<input type="number" value="6" class="multiply-this"/>
<input type="number" value="7" class="multiply-this"/>
JavaScript
function multiply(first){
var value = +first.value;
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
if(textbox.attributes.initialValue){
textbox.value = textbox.attributes.initialValue.value;
} else {
textbox.setAttribute("initialValue", textbox.value);
}
textbox.value = +textbox.value * value;
}
}
window.onload = function(){
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
textbox.onkeyup = function(){
this.setAttribute("initialValue", this.value);
}
}
}
I added functionality to remember what value the textboxes had at first. But you can still change it if you specifically change one of the 7 textboxes that gets multiplied.
EDIT
You can also add this if you want it to multiply after changing one of the values:
textbox.onblur = function(){
multiply(document.getElementById("multiplyer"));
}
JSFiddle

Related

How can I pattern match ID only making sure the variable number matches without having to hardcode all of the possibilities?

I've recently become familiar with Jquery selectors....and they work great. Starts with...ends with....
The problem I have currently is that all of my variable names essentially start with similar patterns and end with similar patterns. This ID is generated from somewhere else so I'm hoping I can do something to use it effectively.
The pattern ID format essentially looks like...
"#id_newbudgetlineitem_set-0-line_item_october"
"#id_newbudgetlineitem_set-0-line_item_november"
"#id_newbudgetlineitem_set-0-line_item_december"
I want to essentially matching on the set-* but only if it's identical to the other ids in my array. Is this even possible without having to hard code anywhere from set-0 to set-1000? Unfortunately the class for each one is the same as is the name situation. Is there someway to say if the set numbers all match in a given array then add them up? I can't use starts with or ends with in this case...and don't want to hardcode 1000 possibilities. Thanks in advance for any ideas or thoughts.
I am trying to do something like.....
function update_total()
{
var total = 0;
$('.budget').each(function(index, element) {
"#id_newbudgetlineitem_set-0-line_item_october" +
"#id_newbudgetlineitem_set-0-line_item_november" +
"#id_newbudgetlineitem_set-0-line_item_december"
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$("#id_total").val(total);
}
Here's a working solution........
function update_total_total_total()
{
var ret = +$("input[name$='set-0-line_item_january']").val() + +$("input[name$='set-0-line_item_february']").val() + +$("input[name$='set-0-line_item_march']").val() + +$("input[name$='set-0-line_item_april']").val() + +$("input[name$='set-0-line_item_may']").val() + +$("input[name$='set-0-line_item_june']").val() + +$("input[name$='set-0-line_item_july']").val() + +$("input[name$='set-0-line_item_august']").val() + +$("input[name$='set-0-line_item_september']").val() + +$("input[name$='set-0-line_item_october']").val() + +$("input[name$='set-0-line_item_november']").val() + +$("input[name$='set-0-line_item_december']").val();
$("input[name$='set-0-line_item_total']").val(ret);
}
But I could have up to 1000 different set values. Is there some other way to do this without having to hard code this 999 more times?
This is a lot closer....but total still says 0. It's updating all of the totals to 0...so that's progress but not getting the actual totals. Forward progress thanks to Swati.
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[id$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
You can get length of total input whose name ends with line_item_total so this value will be counter for for-loop.
Then , inside for loop you can use $(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total])`) this will fetch values from all inputs expect the line_total_item then add value on each iteration .
Lastly , use $(`input[name$=set-${i}-line_item_total]`).val(total); to set total inside line_total_item textbox.
Demo Code :
function update_total_total_total() {
//get length of input line_total for each sets..
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
//get all inputs but not line_item _total
$(`input[name*=id_newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if (!isNaN(val)) {
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total); //set value..of input
}
}
update_total_total_total()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
SET 0 :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_november" value="51">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_december" value="15">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-0-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-0-line_item_description">
</div>
<br/>
<div>
SET 1
<input type="text" name="id_newbudgetlineitem_set-1-line_item_october" value="5">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_december" value="534">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-1-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-1-line_item_description">
</div>
<br/>
<div>
SET 2
<input type="text" name="id_newbudgetlineitem_set-2-line_item_december" value="4">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_oct" value="5">
<br/> Total :
<input type="text" name="id_newbudgetlineitem_set-2-line_item_total" value="" placeholder="total">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_cost_center">
<input type="text" name="id_newbudgetlineitem_set-2-line_item_description">
</div>
This was the final working code. As Swati suggested it was an incorrect name reference.
function update_total_total_total() {
for (var i = 0; i < $("[name$=line_item_total]").length; i++) {
var total = 0;
$(`input[name*=newbudgetlineitem_set-${i}-line_item]:not([name$=line_item_total]):not([name$=line_item_cost_center]):not([name$=line_item_description])`).each(function(i, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
})
$(`input[name$=set-${i}-line_item_total]`).val(total);
}
}

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

Change html slider step exponentially

I am trying to change the slider step by the power of 10 on each slide but it's not working correctly. I am unsure if I should use stepUp() or change the value of value of step directly.
This is how I increment by the power of 10:
var increment = (function(n) {
return function() {
n = n + 2;
var x = Math.pow(10, n);
console.log(x +" " + "Math.Pow thingy");
return x;
}
Here is how I try to pass it as an argument:
document.getElementById("something").stepUp(increment);
In case anyone is wondering, here is the stepUp() that I am using.
Also, here is a fiddle of my slider: Slider Fiddle #1
I want my slider to step to change to 10,100,1000,10000 on each slide.
Pretty sure you can't really do it your way, you'll need to do some kind of calculation yourself. Step only works for constant numbers
var input = document.getElementById("input")
var output = document.getElementById("output")
function getValue() {
let power = input.value
let result = Math.pow(10, +power)
output.value = result
}
<input id="input" type="range" min="1" max="10" value="1" oninput="getValue()" />
<input type="text" id="output" value="10"/>
The natural behaviour of <input type="range" /> is linear, so you have to engineer the required mapping of natural values to required values.
What you are looking for is slider with a socalled log-linear action such that the slider is set up to yield the logarithm of the values you ultimately want;
<input id="something" name="something" type="range" min="2" max="5" value="3" step="1" class="form-control slider" />
Here, the critical settings are
min="2" - log-base10(100) == 2
max="5" - log-base10(100000) == 5
value="3" - log-base10(1000) == 3
Then to get back to the values you actually want, you have to do an anti-logarithm, or Math.pow(10, x).
var slider = document.getElementById('something');
var output = document.getElementById('demo');
slider.onchange = function() {
output.innerHTML = Math.pow(10, this.value);
}
slider.onchange(); // set output for the initial value
DEMO
EDIT:
The behaviour of an <input type="range" /> slider element is inescapably linear. At its current state of development, HTML offers nothing else.
In order to submit the value you actually want, you can use your slider field as the UI for an underlying hidden field, the value of which is maintained to hold a transform of the linear element's value. Providing you can write code to perform the transformation, you are in business. In this case, it's simple - antilogarithm.
So your HTML might be something like this :
<input id="something-ui" type="range" min="2" max="5" value="3" step="1" class="form-control slider" />
<input id="something-hidden" name="something" type="hidden" />
And the corresponding javascript :
var slider = document.getElementById('something-ui');
var hidden = document.getElementById('something-hidden');
var output = document.getElementById('demo');
slider.oninput = function() { // or onChange
output.innerHTML = hidden.value = Math.pow(10, this.value); // antilogarithm
}
slider.oninput(); // set hidden value and output for the initial value
So now, the UI control still behaves linearly but is given (by demo) the appearance, and a submit behaviour (by something-hidden), of being exponential.
This is one way to do this
// Get DOM refs for the required elements
var slider = document.getElementById('myRange');
var res = document.getElementById('res');
var inc = document.getElementById('inc');
// Initialize Div to show starting value
res.innerHTML = slider.value;
// Register on change handler to update div value if slider is changed
slider.onchange = function(){
res.innerHTML = this.value;
}
// Register a click handler inside a closure to increment exponentially
inc.onclick = (function(){
// Initial increment value
var n = 1;
// Return a click handler function which has access to the variable n because of the closure
return function(){
// Button is clicked, increment by n
slider.stepUp(n);
// Update div value for display
res.innerHTML = slider.value;
// Multilply n by 10 so the next time the increment is 10x
n *= 10;
}
})()
<input type="range" id="myRange" value="1000" min="1" max="1000">
<div id="res"></div>
<button id="inc">Increment</button>

sum string with number onclick

I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />&nbsp Ekstra Bed <input type="checkbox" value="50000" />&nbsp Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);

Categories

Resources