I have a div that has multiple input fields. My HTML looks like this:
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" onclick="getAllValues();" />
After I click the image, it must get all the values inside the mainDiv. How can I do this?
$("#getallvalues").click(function() {
var values = $("#mainDiv input").map(function() {
return $(this).val()
}).get().join(",");
console.log(values)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
Loop through each input then get the value and use .map()
var price = 0;
var tax = 0;
var others = 0;
$("#getallvalues").click(function() {
$("#mainDiv input").each(function() {
if ($(this).attr("id") == "price") {
price = $(this).val()
}
if ($(this).attr("id") == "tax") {
tax = $(this).val()
}
if ($(this).attr("id") == "others") {
others = $(this).val()
}
})
console.log("price " + price)
console.log("tax " + tax)
console.log("others " + others)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
You can use .map() to iterate over element and return the value in call back along with .get() to get them in array:
function getAllValues(){
$('#mainDiv input').map({
return this.value;
}).get(); // Output: ["priceval","taxval","otherval"]
}
You can use above array to create the data in whichever format(csv,json,etc) you want for further processing.
Loop through all the inputs in mainDiv
$('#mainDiv input').each(function(){
// Do what ever
})
Another way of doing this is like follows:
$('#mainDiv').find('input').each(function (index, element) {
var yourValue = element.value; // or $(element).val();
// And rest of your code
});
$('#mainDiv input').each(function(){
console.log(this.val());
})
Related
I'm trying to do loop over all tag with same className and get their value:
var quantity = [];
$(".add_more_items").each(function(){
quantity.push($(this).val());
});
this is a result, for example:
['1', '9', '1']
but my problem is I'm trying to set value from this array to other input with same class:
$.each(quantity, function(index, val){
$(".items_final").val(val);
});
but always set in all inputs last value from my array, i don´t know what I'm doing wrong.
Use an index assuming there is 1 to 1 mapping between the fields
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Add more</h3>
<input type="text" value="1" class="add_more_items" />
<input type="text" value="2" class="add_more_items" />
<input type="text" value="3" class="add_more_items" />
<input type="text" value="4" class="add_more_items" />
<hr/>
<h3>final</h3>
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
Also this is useful:
const quantity = $(".add_more_items").map(function(){
return this.value; // or $(this).val()
}).get();
Please help me figure out why only the last input id gets its value added to the input id= #attr3 with keyup.
I need both inputs in the div to have their values put into the input outside the div separated with a comma(,). i made a fiddle https://jsfiddle.net/dc6v6gjd/1/. Thanks
<div id ="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
$(document).ready(function () {
var text = $("#candy :input").map(function () {
return this.id;
}).get();
var attr = [];
for (i=0; i<text.length; i++) {
attr.push('#'+ text[i]);
}
var mat = attr.join(", ");
$(mat).keyup(function(){
update();
function update() {
attr.forEach(function(index, i){
// alert(i);
$("#attr3").val( $(attr[i]).val() + "," );
});
}
});
});
The reason is you're overriding the value of attr3 on each iteration of forEach. You could instead use join to get the value.
e.g.
function update() {
var val = attr
.map(function(a) {
return $(a).val();
})
.join(",");
$("#attr3").val(val);
}
That being said I'd probably go with a simpler solution like this.
// set the keyup event handler and add all inputs to an array.
var inputs = $("#candy :input").keyup(function() {
update();
}).get();
// read all input values into comma separated string and update attr3
function update() {
var val = inputs.map(function(i) {
return $(i).val();
}).join(",");
$("#attr3").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
Update: Support dynamically added inputs.
$(document).on("keyup", "#candy :input", function() {
update();
});
function update() {
var val = $("#candy :input").get().map(function(i) {
return $(i).val();
}).join(",");
$("#attrFinal").val(val);
}
var count = 3;
$("#add").click(function() {
$("#candy").append("<input type='text' id='attr" + count++ + "' name='emailAddress' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attrFinal" name="username" value="">
<button id="add">Add New</button>
<input type="text" name="members[0].name">
<input type="text" name="members[0].address">
Javascript code :
var input_text;
var inputs=document.querySelectorAll("input[type=text],textarea, select");
_.each(inputs, function(e, i) {
var keyName = $(e).attr("name");
if (typeof keyName != "undefined") {
var text = $(e).parent().find('label').text();
if ($(e).is('select')) {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).find(':selected').text() + "</td></tr>";
}
else {
input_text = input_text + "<tr><td>" + text + "</td><td> " + $(e).val() + "</td></tr>";
}
}
});
console.log(input_text);
As You can see, I m getting the values of all the inputs in $(e).val() except those above mentioned inputs.
Those inputs aren't an "array" in the browser. They just use a naming convention in their name which is used by some server-side handling (for instance, in PHP) to organize the form data for you when it's submitted.
I don't know what you mean by "previewing," but you can see the values of those elements by simply looping through the elements of your form (yourForm.elements), or by using yourForm.querySelectorAll("input[type=text]") (or $(yourForm).find("input[type=text]") using jQuery — I missed the jquery tag on your question at first).
Example of theForm.elements:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.elements, function(element) {
if (element.type === "text") {
console.log(element.name + " = " + element.value);
}
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of theForm.querySelectorAll:
document.querySelector("form input[type=button]").addEventListener("click", function() {
var form = document.getElementById("the-form");
Array.prototype.forEach.call(form.querySelectorAll("input[type=text]"), function(element) {
console.log(element.name + " = " + element.value);
});
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
Example of $(theForm).find:
$("form input[type=button]").on("click", function() {
var form = document.getElementById("the-form");
$(form).find("input[type=text]").each(function() {
console.log(this.name + " = " + this.value);
});
// Of course, we could have just used `$("#the-form input[type=text]").each`...
// but I was assuming you'd already have `form`
});
<form id="the-form">
<input type="text" name="members[0].name" value="name 0">
<input type="text" name="members[0].address" value="address 0">
<input type="text" name="members[1].name" value="name 1">
<input type="text" name="members[1].address" value="address 1">
<input type="text" name="members[2].name" value="name 2">
<input type="text" name="members[2].address" value="address 2">
<div>
<input type="button" value="Show">
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So many ways to get the input type values using formID
$('#formId input, #formId select').each(
function(index){
var input = $(this);
}
);
OR
var formElements = new Array();
$("form :input").each(function(){
formElements.push($(this));
});
OR
var $form_elements = $("#form_id").find(":input");
hope it helps you.
You can use serializeArray or serialize for it .
$("form").serializeArray();
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Doc
I have a question I'm trying to figure out...
I have a lot of inputs in a form, but I only need to iterate through the ones in the div with player class.
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
What I need is to iterate through them all once an input field has been modified and calculate how many of the input fields have 0 in them and if its 1 or more than 4 disable submit button.
I've been trying like this but it doesn't seem to work
$(document).ready(function()
{
$(function()
{
var $sum = parseInt($("#sum").text(), 10);
var $num = 0;
if(($sum == 0))
{
$("button[name=submit2]").attr("disabled", "disabled");
}
$(".player input[type=text]").bind("DOMSubtreeModified", function()
{
$.each($("input[type=text]"),function(){
if (!isNaN(+this.value))
{
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
});
})
});
I've also tried
$(document).ready(function(){
$(".unit").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".unit").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
});
if (($num > 4) || ($num == 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Try changing
if(!isNaN(this.value) && this.value.length!=0) {
++$num;
}
with
if($(this).val() != "" && $(this).val() !=0) {
++$num;
}
to be more jQuery style
I guess this is what you want :
// control function
function checkInputs() {
var num = 0;
// foreach inputs
$(".player input").each(function(i,item) {
var value = $(this).val();
if (value.trim() === "0") {
num++;
}
});
if (num === 1 || num > 4) {
$("#myForm input[type='submit']").attr("disabled", "true");
} else {
$("#myForm input[type='submit']").removeAttr("disabled");
}
}
// if you want a first check after loading the page :
checkInputs();
$(".player input").change(
// This function will be called each time an input change in the player div
checkInputs
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myForm">
<div class="player">
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
<input type="text" value="0" class="unit" />
</div>
<input type="submit"/>
</form>
I am not sure why are you checking the length? this.value.length!=0
I tweaked your code, here is the fiddle link : http://jsfiddle.net/bLa6evpg/
Hope this help!
I couldn't follow your function, but I believe your problem is that you are running it on page load, and not on the onchange of your input boxes. I achieved the desired functionality by doing that in this codepen
html:
<div class="player">
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number"/>
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
<input type="text" value="0" class="unit" onchange="validateChanges()" type="number" />
</div>
<button name="submit2">Click</button>
JS:
function validateChanges() {
var playerDiv = document.getElementsByClassName("player")[0];
var inputs = playerDiv.getElementsByTagName("input");
var total = 0;
for(var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if(total == 1 || total > 4) { // IF total is 1 or more then 4
document.getElementsByTagName("button")[0].disabled = true;
} else {
document.getElementsByTagName("button")[0].disabled = false;
}
}
looks like i was almost right just messed up a bit Silent_coder fixed this +i added some tricks i saw here
$(document).ready(function(){
CheckNull();
$(".player input").each(function() {
$(this).keyup(function(){
CheckNull();
});
});
function CheckNull() {
var $num = 0;
$(".player input").each(function() {
if(this.value != 0 ) {
$num++;
}
});
if (($num > 4) || ($num <= 1))
$("button[name=submit2]").attr("disabled", "disabled");
else
$("button[name=submit2]").removeAttr("disabled");
}
});
Works like i charm for me ^^
Here is a JsFiddle example
$(function () {
$('.unit').on('change', function () {
var units = 0;
$('.unit').each(function (index, value) {
var unit = parseInt($(value).val(),10);
units += unit;
if(units >= 4 || units === 1) {
$('form > button').prop('disabled', true);
} else {
$('form > button').prop('disabled', false);
}
});
});
});
I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>