I have multiple <div>s, based on a <select>, where each one contains multiple <input>s and sometimes a disabled <select> with a fixed value. Now I'm trying to loop through each of the divs and put all inputs and select values into an array and push that array into the "master" array.
However this seems not to work to well.
I feel like I'm already close but yet so far. :(
var dummy = [];
for(var i = 1; i <= toSend.count; i++){
var temp = [];
$("div[data-row="+i+"]").children('input, select').each(function(){
temp.push( $(this).val() );
});
dummy.push(temp);
};
console.log(dummy);
toSend.count is the counting of how many div's with data-row exist.
The HTML looks like this :
<div id="container">
<div data-row="1">
<input type="text"/>
<input type="text"/>
</div>
<div data-row="2">
<input type="text"/>
<input type="text"/>
</div>
</div>
Aaah, nevermind this was my own stupidity! I'm generating the div's via AJAX
and I copy pasted myself an error.
All div's had data-row=1, no wonder it packed all in one array >.<
(Edit: pays to read the code more completely)
Since the toSend variable is just the DIVs with a data-row attribute, no need to loop over toSend to find the DIVs:
var dummy = [];
$("#container div[data-row]").each(function() {
var temp = [];
$(this).children("input, select").each(function() {
temp.push(this.value);
});
dummy.push(temp);
});
After this, you might not even need the toSend variable at all.
Brief code for what you want to achieve.
$("div[data-row="+i+"]")each(function(){
$(this).children('input, select').each(function(){
console.log( $(this).val());
console.log("Child Change");
});
console.log("Div Change");
});
.each function from jquery is not syncrounious, use for instead.
var $tmp;
for(var i = 1; i <= toSend.count; i++)
{
$tmp = $("div[data-row="+i+"]").children('input, select');
for(var ii = 1,len = $tmp.length; ii <= len; ii++){
console.log( $tmp.eq(ii).val());
};
console.log("New line #" + i);
};
Related
i want to use document.querySelector("#") on an input element (and check if it is chekced of) that is saved in a string, and then retrieved by innerHTML. however i cant figure out how to get acesess to it?
i want to run through the array, and be able to log when the radio button is checked off. to do so, i have tried using queryselectorAll("radio") an array with querySelector and the different ids for the different radio button, but i dosent seem to work
<body>
<div class="stemmegiving"> </div>
<script>
var stemmegivingEl= document.querySelector(".stemmegiving")
var alt=['<input type="radio" name="stem" class="kanpper" checked id=" Rødt" >',
'<input type="radio" name="stem" value=""class="kanpper"id="SP"> ',
'<input type="radio" name="stem" value=""class="kanpper"id="AP"> ']
for (var i = 0; i < alt.length; i++) {
stemmegivingEl.innerHTML+= alt[i]
}
var giStemmeEl = document.querySelector("#giStemme")
var alt2=[document.querySelector("#rødt"), document.querySelector("#SV"),document.querySelector("#AP")]
for (var i = 0; i < alt.length; i++) {
if (alt2[i].checked) {
console.log(alt2[i] + " is true");
console.log(typeof alt2[i]);
}
else {
console.log(i + "not true");
console.log(typeof alt2[i]);
}
}
</script>
</body>
i would like to be able to access it the same way as if you
make an input element in body and then querySelect it
If you use jQuery, you can parse html on the fly and then you'd have that query selector functionality you want.
$(alt[i]).prop('checked');
https://api.jquery.com/jquery.parsehtml/
The mandatory div id gets different numbers of inputs field displayed in it dynamically. Each input field starting from the first gets an id attr1, then attr2,..attr[n]. I need a way to get this into an array that gets the value of each input field with keyup and puts them into a separate input field with id detail.
This code works but returns undefined in some case when the hard coded input field ids exceed the generated input field ids. Thanks.
<div id="attributes"> <!--Start of Div Refreshed on Ajax Page Refresh-->
<div id="mandatory">
</div>
</div>
var total = '#attr1, #attr2';
$("#attributes").on('keyup', total, function(){
update();
})
function update() {
$("#detail").val($('#attr1').val() + "," $('#attr2').val());
}
If I understood right your question I think you're looking for something like that:
var fields = $("#mandatory").find("input"),
ids = [];
fields.each(function(){
$(this).on("keyup", function(){
var val = "";
ids = [];
fields.each(function(){
val += $(this).val() + (fields.length === ($(this).index() + 1) ? "": ", ");
ids.push($(this).get(0).id);
});
$("#detail").val(val);
console.log(ids)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="attributes">
<div id="mandatory">
<input id="one" class="one" value="54"/>
<input id="two" class="two" value="55"/>
<input id="three" class="three" value="587"/>
</div>
</div>
<input id="detail" type="text" />
I'm not sure if this is what you're looking for, but I think it'll take you down the right path. In this example, any time a text input field is generated, an input event handler is attached to it that changes the value of a main textarea. If this isn't quite what you're looking for, please let me know and I'll be happy to try to work it out more.
document.getElementById('adder').onclick = function() {
var dynamicTextbox = document.createElement('input');
dynamicTextbox.setAttribute('type', 'text');
dynamicTextbox.setAttribute('class', 'dynamicText');
dynamicTextbox.addEventListener("input", function() {
var allTextboxes = document.getElementsByClassName('dynamicText');
var allValues = '';
for (var i=0; i < allTextboxes.length; i++) {
allValues += allTextboxes[i].value;
}
document.getElementById('detail').value = allValues;
});
document.getElementById('textboxes').appendChild(dynamicTextbox);
}
<textarea id="detail"></textarea>
<input id="adder" type="button" value="Add Text Field" />
<div id="textboxes"></div>
I'm java script beginner, so do not be angry against me ;)
In order to simplify my code, I would like to generate automatically variables and affect them their current value in order to use them further.
What I have done and works (but I have a lot of changing variable on various documents) :
Html : input a,b,c,... with id a,b,c,...
a = Number($('#a').val());
b = Number($('#a').val());
c = Number($('#c').val());
...
What I'm trying to do :
Html : add a class 'test' to all inputs I want to generate
var elements = document.getElementsByClassName('test');
elementsLength = elements.length;
for (var i = 0 ; i < elementsLength ; i++) {
elements[i].value = Number($("#"+elements[i].id).val());
}
Something must be wrong in the part elements[i].value = Number($("#"+elements[i].id).val());
because when I call the variable a, b or c, it has not been generated.
after the loop,
alert (a);
returns [object HTMLInputElement] instead of the value I would like to get ;(
I'm searching since yesterday, I'm loose.
Thank you for your support guys.
++
Seems you want to persist the value of INPUTS in variable. I would suggest you to create an object i.e. obj and create properties based on input.
var obj = {};
$('button').on('click', function() {
$('.test').each(function() {
obj[$(this).prop('id')] = Number($(this).val());
});
//For debugging
console.clear();
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" class="test">
<input type="text" id="b" class="test">
<input type="text" id="c" class="test">
<button type="button">Click me</button>
In one of the jsp pages from my project, I have to work with this json lists:
var obj_tipo = jQuery.parseJSON( "{"Tipo":[{"id":3,"nome":"gerente"},{"id":4,"nome":"supervisor"},{"id":5,"nome":"analista"},{"id":6,"nome":"tecnico"},{"id":7,"nome":"secretaria"},{"id":8,"nome":"seguranca"}]}" );
var obj_campo = jQuery.parseJSON( "{"Key":[{"id":1,"nome":"e-mail"},{"id":2,"nome":"cidade"}]}" );
I try read each item of the list this way:
for(var item in obj_tipo.Tipo)
select.append('<option value="'+item.nome+'">'+item.nome+'</option>');
and
for(var item in obj_campo.Key)
$("table.cadastro").append('<tr> <td> '+item.nome+' : </td> <td> <input type="text" name="'+item.nome+'" size=20 maxlenght=40> </td> <tr>');
But I am getting the text 'undefined' when I display the page, instead of the corret text, despite the fact that the right amount of itens are being displayed.
Someone knows how to fix that? What the right way to access each item from my json list? the list is well formed, right?
As #Oleg said, it should be more like:
var obj_tipo = jQuery.parseJSON( '{"Tipo":[{"id":3,"nome":"gerente"},{"id":4,"nome":"supervisor"},{"id":5,"nome":"analista"},{"id":6,"nome":"tecnico"},{"id":7,"nome":"secretaria"},{"id":8,"nome":"seguranca"}]}' );
var obj_campo = jQuery.parseJSON( '{"Key":[{"id":1,"nome":"e-mail"},{"id":2,"nome":"cidade"}]}' );
I basically just changed the wrapping quotes, to '
Also, you may want to consider looping through the JSON using $.each, if you are using jQuery. See this question here for some clarification: jquery loop on Json data using $.each
Using for in on arrays is not a good idea. Either use for (var i = 0; i < arr.length; i++) {... or native forEach or jQuery's each...
var obj = $.parseJSON('{"Tipo":[{...},{...},{...}]}'); // mind the quotes
$.each(obj.Tipo, function (index, item) {
select.append('<option value="' + item.nome + '">' + item.nome + '</option>');
});
Use
for(var item in obj_tipo.Tipo) {
var nome= obj_tipo.Tipo[item].nome;
select.append('<option value="'+nome+'">'+ nome +'</option>');
}
instead of
for(var item in obj_tipo.Tipo)
select.append('<option value="'+item.nome+'">'+item.nome+'</option>');
For more info visit for...in
variable: A different property name is assigned to variable on each iteration.
I don't have any idea about Java language. But you can get the Nome and id field by using below code snippet.
Please try with the below code snippet. Let me know if any concern.
var tipo = obj_tipo.Tipo;
for(var i = 0; i < tipo.Length; i++)
{
select.append('<option value="'+tipo[i].id+'">'+tipo[i].nome+'</option>');
}
The item in your code returns the index of the array. I updated your code to get to a solution. Please find the fiddle here
$("table.cadastro").append('<tr> <td> '+obj_campo.Key[item].nome+' : </td> <td> <input type="text" name="'+obj_campo.Key[item].nome+'" size=20 maxlenght=40> </td> <tr>');
or
for(var item in obj_tipo.Tipo)
$('select').append('<option value="'+obj_tipo.Tipo[item].nome+'">'+obj_tipo.Tipo[item].nome+'</option>');
I am trying to use jquery to iterate through all '.invoice-lines' and generate a total by summing up all values in the '.amount-input' div.
AJAX dynamically generates the default values in '.amount-input' which can be manually changed by the user. I have been trying to create a function so that every time new data comes in using AJAX, a call will be made to the function updateTotal(), which iterates through all the non-empty 'amount-input' values and recalculates the total. I have been having a really tough time accomplishing this, and I would greatly appreciate any help.
JQuery - This is my jquery so far (pseudo code)
function updateTotal(){
var total=0;
for(i=0; i < $('.invoice-line').length; i++){
if($('.amount-input').eq(i).val() != empty)){
total += $('.amount-input').eq(i).val();
}
}
$('.total').val("$" + total);
}
Markup
<?
for(i=0; i < 25; i++){
echo' <div class="invoice-line">
<div class="prod-id-cell"><input type="text" class="prod-id-input"></div>
<div class="amount-cell"><input class="amount-input" type="text" /></div>
</div>';
}
?>
<div class="total">$0.00</div>
Make sure you cache the jQuery selection, otherwise you are doing 50 DOM traversals instead of 1:
var total=0, amounts = $('.amount-input'), len = amounts.length;
for(var i=0; i < len; i++){
total += +amounts[i].value;
}
Use the unary plus operator to convert the cell value from a string to a number. +"" will give you zero, so you don't need to check if the cell is empty, though you may want to check isNaN when validating the input.
Also, use val for input elements, but text for divs or spans.
$('.total').text("$" + total);
The basic syntax in pure JS is as follows:
var inputs = document.getElementsByClassName("amount-input");
var total = 0;
inputs.forEach(function (input) {
total += value;
});
The idea is that you get a collection of all the inputs in which you are interested, and then sum up the values using an external variable. If you wanted to expand this to include other inputs then you could use document.querySelectorAll("") with a CSS query selector to get the collection. (This is the same as the jQuery $("") selection syntax.)
Something like this should work:
function updateTotal() {
var total = 0;
$('.invoice-line').each(function (i, elem) {
total += parseFloat($(elem).find('.amount-input').val(), 10) || 0;
});
$('.total').val("$" + total);
}
You can use the change event to update the total amount everytime an input element is individually updated. Below is a simple example:
HTML:
<input class="invoice" type="text" value="0" />
<input class="invoice" type="text" value="0" />
<input class="invoice" type="text" value="0" />
<div id="total">0</div>
Javascript:
$('.invoice').change(function() {
var total = 0;
$('.invoice').each(function() {
total += parseFloat($(this).val());
});
$('#total').text(total);
});
You can see it working in this jsfiddle.
Shortly after posting, I was able to come up with my own solution as follows:
function updateTotal(){
var total=0;
for(i=0; i < $('.invoice-line').size(); i++){
currentAmount = Number($('.amount-input').eq(i).val().replace(/[^0-9\.]+/g,""));
total += currentAmount;
}
$('.total-number').text("$" + total.toFixed(2));
}