Adding value attribut without removing old one - javascript

Is it possible to add value atribute through jquery, but not to remove the old atribut (something like addClass).I have 7 input fields that is typed, and need to combine it in one word and passed to another input field. I tried to take value from typed field and passed it to field that all of them need to be combined, but it always take value from last field when I tried with
$("input").keyup(function(){
var test = this.value;
$(".solution_2").attr('value', test);
});
Here is html:
<input id="1" class="q1 inputs letter square border_black" maxlength="1" type="text"/>
<input id="2" class="q2 inputs letter square border_black" maxlength="1" type="text" />
<input class="solution_2" value="" class="form-control" type="text" name="date">
Any ideas. Thanks.

You should use map and join to get all the values. So, you don't need to store or add value in different attribute. Check the below code:
$("button").on('click', function() {
var finalValue = $('input').map(function() {
return this.value;
}).get().join('');
console.log(finalValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="1" class="q1 inputs letter square border_black" maxlength="1" type="text" />
<input id="2" class="q2 inputs letter square border_black" maxlength="1" type="text" />
<input class="solution_2" value="" class="form-control" type="text" name="date">
<button class="someClass">Get Value</button>

First you usually get the value in jquery by using .val().
The problem is that you only take the last value and overwrite the old one. You need to take the old value and add the new one.
$("input").keyup(function(){
$(".solution_2").val($(".solution_2").val()+this.val());
});

You could just get all the value evrytime and send them to solution_2
Something like :
$("input").keyup(function(){
var test = $("#1").attr("value")+$("#2").attr("value");
$(".solution_2").attr('value', test);
});
Btw, you can use val() instead of attr("value");
$("input").keyup(function(){
var test = $("#1").val()+$("#2").val();
$(".solution_2").val(test);
});

Do you mean to concatinate the inputs values into a single string?
var inputs = $('.inputs');
inputs.keyup(function() {
$('.solution_2').val(inputs.val().join(''));
});

Try This :
$(document).ready(function() {
$('input').on('input',function(){
var txt = '';
$('.solution_2').val('');
$('input').each(function(){
txt += $(this).val();
})
$('.solution_2').val(txt);
})
})
$(document).ready(function() {
$('input').on('input',function(){
var txt = '';
$('.solution_2').val('');
$('input').each(function(){
txt += $(this).val();
})
$('.solution_2').val(txt);
})
})
<!-- begin snippet: js hide: true console: false babel: false -->
p {
display: table-row;
}
input,label {
display: table-cell;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p><label>character 1:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 2:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 3:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 4:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 5:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 6:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 7:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>word:</label><input class="solution_2" value="" class="form-control" type="text" name="date"></p>

Related

How to calculate form fields values to update hidden field value?

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

HTML form:input calculate 2 fields

I'm using spring mvc for my form which has the tag
<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />
<input type="text" disabled="disabled" id="result" />
I read some questions in regards to calculations and even found a js fiddle:
http://jsfiddle.net/g7zz6/1125/
how do i calculate 2 input fields and put results in 3rd input field
but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?
Here you go
HTML
<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">
JS
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var val1 = parseInt($('.value1').val());
var val2 = parseInt($('.value2').val());
var sum = val1+val2;
$("input#result").val(sum);
});
});
Fiddle https://jsfiddle.net/1sbvfzcc/
$(document).ready(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
$('.input').blur(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">
Please check the code this might help you understand why your code is not working.
You are using document ready function which is not able to get the value as no default value for input box.
I have added a new blur function which will calculate the value on change of input box
Try this your form tag syntax was wrong
$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>
<input type="text" disabled="disabled" id="result" />

Extract the Id's number of multiple elements jQuery

I have this simple code:
$('[id^=pz]').change(function() {
//Getting the numbers after the letters "pz":
//1
//2
//100
});
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
How to retrieve the number of each element?
Thanks.
You can use the match function:
var m = $(this).attr('id').match("pz([0-9]+)"); // m = ["pz1", "1"]
var num = m[1];
match takes a regex and returns the input matching the regex as well as possible capturing groups (i.e. the things matching the parts in parentheses).
Note: in latest jQuery, use prop() instead of attr().
$('[id^=pz]').change(function() {
console.log($(this).attr("id").split("pz")[1])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
$('[id^=pz]').change(function() {
// Getting the numbers after the letters "pz":
console.log(this.id.replace("pz", ""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
On changeing the input you have to use document.querySelectorAll() to get all the elements first.Then use forEach to get the value of id for each element and match the require numbers using regular expression.
$('[id^=pz]').change(function() {
var pz = document.querySelectorAll('[id^=pz]');
values = [];
pz.forEach(function(pz){
values.push(pz.getAttribute('id'));
})
values.forEach(function(value){
console.log(value.match(/(?!pz)\d+/g)[0]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
Just do this ;)
$('[id^=pz]').change(function(event) {
// with substr must have 2 chars
var id = event.target.id.substr(2);
console.log('substr', id)
// with regexp
var id2 = event.target.id.match('[0-9]+')[0];
console.log('regexp', id2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz1000000">
<input type="text" id="pzdsfg1000000">
Here you go. Use Array#match with simple RegExp.
Click on any input to reveal it's number.
$('input').click(function(){
console.log($(this).attr('id').match(/(?!pz)\d+/g)[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
<input type="text" id="pwadawdz7">
<input type="text" id="random98">
Might be a better solution to have the id as a data attribute so you do not need to rip it out of the id.
$("[data-pz]").on("change", function(){
var elem = $(this);
console.log(elem.data("pz"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-pz="1"/>
<input data-pz="10"/>
<input data-pz="100"/>
You can use regular expressions, like this:
$.each($('[id^=pz]'), function (_, item) {
var match = item.id.match(/pz(\d+)/);
if(match) {
console.log(match[1]);
}
});

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Change $(this) input field color based on class effecting all classes in div

I have this HTML that occurs multiple times on a page:
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span></p>
</div>
<div class="col-r">
<div class="qty-days">
<input name="Mon" class="qty-input" value="0" maxlength="2" />
<input name="Tue" class="qty-input" value="0" maxlength="2" />
<input name="Wed" class="qty-input" value="0" maxlength="2" />
<input name="Thu" class="qty-input" value="0" maxlength="2" />
<input name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>
I have this JQuery to detect when the input field is changed and if the value is greater than 0, change the color to red.
$(".qty-input").change(function(){
var qty = parseInt($(this).val());
if(qty > 0){
$(this).css('color','red');
}
else{
$(this).css('color','black');
}
});
It is behaving very unpredictably. When I change the value of the first input field (Monday), it makes all 5 inputs red. Then sometimes it is changing the colors back to black in completely different rows sets of days. Seems like a simple problem to fix, but having trouble figuring it out.
The problem is that this code:
var qty = $(this).val();
Returns a string. And this code compares that string to a Number
if(qty > 0){
Try changing the first line of code to:
if ($(this).val()) {
var qty = parseInt($(this).val(), 10);
}
And it should start to work more consistently but you will also want to validate that the input is all numbers.
Thanks for all the responses. It prompted me to dig deeper at which point I discovered another piece of code in a different JS file that was trying (incorrectly!) to do the same thing. The code I have above is in fact sound and works perfectly. I apologize for wasting anyone's time here. I didn't realize that my client had a developer who had already attempted to do this (and who also put the code in the wrong file).
Use change event target to get to the element
$(document).ready(function() {
$(".qty-input").change(function(e) {
var target = e.target;
var qty = $(target).val();
if (qty > 0) {
$(target).css('color', 'red');
} else {
$(target).css('color', 'black');
}
alert("value is " + qty)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span>
</p>
</div>
<div class="col-r">
<div class="qty-days">
<input type="text" name="Mon" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Tue" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Wed" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Thu" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>

Categories

Resources