In a for loop based on divs count I need to select each div child so I got to get the id of the div.
this is what I have tried:
var json = [{
'orderId': order,
'attributes': [],
'services': []
}];
var divLength = $('#stepchild div').length;
for (i = 0; i < divLength; i++) {
var fields = {};
$('#divID input').each(function() {
fields[this.name] = $(this).val();
})
$('#divID select').each(function() {
fields[this.name] = $(this).val();
})
json[0]['attributes'].push(fields);
}
<div id="form0">
<input type="text" class="field1">
</div>
<div id="form1">
<input type="text" class="field1">
</div>
<div id="form2">
<input type="text" class="field1">
</div>
You can use a loop like this (basic example):
$('div').each(function()
{
console.log($(this).attr('id'))
})
refs:
https://api.jquery.com/attr/
https://api.jquery.com/jQuery.each/
$('target').each(function()
{
console.log($(this).attr('id'))
});
this will run for each target match . in your case 'div' is your target . you can use find , child attribute for sub search
Welcome to Stack Overflow
You need to use map function here in order to collect ID or value inside the textbox.
Here is an example to get ID:
var json = [{
'orderId': 'order',
'attributes': [],
'services': []
}];
function getDivID()
{
var values = $("#stepchild div").map(function (i, e) {
return $(e).attr('id');
}).get();
json[0]['attributes'].push(values);
console.log("json[0]['attributes'] is now : " + json[0]['attributes']);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="stepchild">
<div id="form0">
<input type="text" class="field1">
</div>
<div id="form1">
<input type="text" class="field1">
</div>
<div id="form2">
<input type="text" class="field1">
</div>
</div>
<button onclick="getDivID()">Click here to get div ID</button>
Using .map() function you can also collect value form each element inside div :
var json = [{
'orderId': 'order',
'attributes': [],
'services': []
}];
function getValue() {
var values = $("#stepchild input").map(function (i, e) {
return $(e).val();
}).get();
json[0]['attributes'].push(values);
console.log("json[0]['attributes'] is now : " + json[0]['attributes']);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="stepchild">
<div id="form0">
<input type="text" class="field1" value="abc">
</div>
<div id="form1">
<input type="text" class="field1" value="xyz">
</div>
<div id="form2">
<input type="text" class="field1" value="something">
</div>
</div>
<button onclick="getValue()">Click here to get value</button>
refs:
http://api.jquery.com/map/
Disclaimer : I know the question is about jquery, but I would like to provide the non-jQuery version :
If you just want the IDs in a list, you can use this :
[...document.querySelectorAll('div')].map(div => div.id)
Or if you need to loop over them and do some processing for each, you can use this :
[...document.querySelectorAll('div')].forEach(div => {
// process the div element here with div.id beeing the ID
});
Within $.fn.each, you can access the current element id with this.id or with the parameter element.id.
Keep in mind that $() will give you a collection. You can write your code like this:
const json = [{
'orderId': order,
'attributes': [],
'services': [],
}];
$('#stepchild div').each(function (index, element) {
let fields = {};
$(element).find('input, select').each(function () {
fields[this.name] = $(this).val();
});
json[0]['attributes'].push(fields);
});
Related
Looks like my main issue was using .val() when I should have been using map, thank you #Barmar!
Though I'm still looking for a way to achieve the second array structure at the bottom of my post. It seems like the HTML structure would have to be:
<div>
<input type="text" name="student[1][name]">
<input type="number" name="student[1][score]">
<input type="text" name="student[2][name]">
<input type="number" name="student[2][score]">
<input type="text" name="student[3][name]">
<input type="number" name="student[3][score]">
</div>
The challenge with this is the ID number is dynamic, so I'm not sure how to fit this in a Jquery selector. Would I just be selecting by "student" i.e.
let input_names = $('input[name^="student["]').map(function() {
return this.value;
}).get();
I have a lot of inputs that are of the same kind so I want them in arrays, i.e.
<div>
<input type="text" name="name_[1]">
<input type="number" name="score_[1]">
<input type="text" name="name_[2]">
<input type="number" name="score_[2]">
<input type="text" name="name_[3]">
<input type="number" name="score_[3]">
</div>
The number in-between the brackets is the ID grouping related elements together. I want to be able to send all the values in arrays in an AJAX request but can't seem to figure it out. Only the first elements get sent, not an array
let input_names = $('input[name^="name_"]').val();
let input_scores = $('input[name^="score_"]').val();
$.ajax({
url: "../util/funcs.php",
async: true,
data: {
a: "backendFunction",
input_names: input_names,
input_scores: input_scores
}
})
.done(function(data) {
console.log("Success");
})
.fail(function() {
console.log("Error");
.always(function() {
// alert( "complete" );
});
I want a way to neatly send them to the backend, either as separate arrays by name parameter or ideally grouped by ID. So the $_REQUEST would look something like:
[ids] =>
[1, 2]
[names] =>
["alex", "john"]
[scores] =>
[30, 70]
Or even better:
[1] =>
[name] => "alex"
[score] => "30"
[2] =>
[name] => "john"
[score] => "70"
Unfortunately either way I try, the AJAX only seems to send the first of each input, rather than arrays. Please help!
.val() only returns the value of the first element that matches the selector, not all of them. You need to loop over all the matches to get all the values.
let input_names = $('input[name^="name["]').map(function() {
return this.value;
}).get();
let input_scores = $('input[name^="score["]').map(function() {
return this.value;
}).get();
Here is a solution to get your desired object format:
$(function() {
let result = $('input').map(function() {
return { name: this.name, value: this.value };
}).get().reduce((acc, obj) => {
let num = obj.name.replace(/[^\d]+/g, '');
let key = obj.name.replace(/_.*$/, '');
if(!acc[num]) {
acc[num] = {};
}
acc[num][key] = obj.value;
return acc;
}, {});
console.log('result:', result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" name="name_[1]" value="Alex">
<input type="number" name="score_[1]" value="101">
<input type="text" name="name_[2]" value="Berta">
<input type="number" name="score_[2]" value="102">
<input type="text" name="name_[3]" value="Dora">
<input type="number" name="score_[3]" value="103">
</div>
Output:
result: {
"1": {
"name": "Alex",
"score": "101"
},
"2": {
"name": "Berta",
"score": "102"
},
"3": {
"name": "Dora",
"score": "103"
}
}
Notes:
first, get all input elements and build an array of { name, value } objects
then, use a .reduce() to accumulate the desired object format
tweak the .replace() of num and key if you have different name input patterns
<input type="text" class="name_">
<input type="number" class="score_">
<input type="text" class="name_">
<input type="number" class="score_">
<input type="text" class="name_">
<input type="number" class="score_">
<input class="submit" type="button" value="submit" />
<script>
$('.submit').click(function(){
nam = $('.name_');
scr = $('.score_');
naml = nam.length;
myar = new Array;
i=0;
for(i=0;i<naml;i+=1)
{
myar[i] = {'name':nam.eq(i).val(),'score':scr.eq(i).val()};
}
alert(JSON.stringify(myar));
});
</script>
I'm using bootstrap validator to cloning the input and radio elements.
It is working fine, but i have issue while receiving these values as JavaScript array. Because i always have hidden input and radio elements in the DOM so it send empty object.
How i map my array object to receive values
var kids = $(".form--group").map(function() {
return {
kidName: $(this).find('.thevoornaam').val(),
newDob: $(this).find('.date_of_birth').val(),
}
}).get();
console.log(kids)
I'm receiving values like this..
[{kidName: "Test", newDob:"20"},{kidName: "", newDob:""} ]
Always receive second object with empty string.
How can remove the object from array if values are empty or undefined is..
I hope you guys understand my question.
Thanks in advance.
You can use filter to filter out the empty object like this
var kids = $(".form--group").map(function() {
return {
kidName: $(this).find('.thevoornaam').val(),
newDob: $(this).find('.date_of_birth').val(),
}
}).get();
kids = kids.filter(function (kid) {
return kid.kidName && kid.newDob;
});
console.log(kids)
If you want to exclude the item when every property is empty, undefined or 0;
let obj = [{kidName: "Test", newDob:"20"},{kidName: "", newDob:""} ];
let filtered = obj.filter(e=>{
for(let p in e){
if(e[p]){
return true;
}
}
});
console.log(filtered);
Check the strings before you create the objects:
$(document).ready(function(){
var kids = $(".form--group").map(function() {
var kidName = $(this).find('.thevoornaam').val();
var dob = $(this).find('.date_of_birth').val();
var result_arr = [];
if(kidName || dob)
{
var obj = {kidName: kidName, newDob: dob}
result_arr.push(obj);
}
return result_arr;
}).get();
console.log(kids)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form--group">
<input class="thevoornaam" value="Test Name" />
<input class="date_of_birth" value="Test Date" />
</div>
<div class="form--group">
<input class="thevoornaam" value="" />
<input class="date_of_birth" value="" />
</div>
<div class="form--group">
<input class="thevoornaam" value="Test Name" />
<input class="date_of_birth" value="Test Date" />
</div>
My form should contain key=>value pair, where key should be labelof the form and value should be details entered by user,
My issue is getting name of the field instead of label,
Expected output:
ENTER YOUR AGE:25
but i m getting output like this:
name-preview : 25;
How can it be achieved for expected output?
var result = [];
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
//console.log(label);
value = $this.siblings().attr('value');
//console.log(value);
result.push({
label: label,
value: value
});
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
>
how can i make for this elements:https://jsfiddle.net/ktgmtwd7/1/
Try this—when you change the the input value then the results array will auto update:
var result = [];
var input;
$('div label').each(function() {
var $this = $(this);
var label = $this.text();
input = $this.next();
result.push({
label: label,
value: input.val()
});
console.log(result);
$this.next().on('keyup', function() {
result = [];
result.push({
label: label,
value: input.val()
});
console.clear()
console.log(result);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="uploaddata.php" method="POST">
<div class="form-group">
<label for="text-1483332101835-preview" class="fb-text-label">enter your age:</label>
<input type="text" class="form-control" name="age" value="25" id="mobNum">
</div>
</form>
<h3></h3>
I have an issue with jsviews. I want to bind an array of elements. Each element is an object. Elements are added dynamicaly. Value of one field of each element computes base on another field. How is it posiible to do without refreshing array every time?
js:
model = {
elements: []
};
$(function() {
$.when($.templates('#tmpl').link('#container', model)
.on('click', '#addElement', function () {
$.observable(model.elements).insert({});
})
).done(function() {
$.observe(model, 'elements', function(e, eventArgs) {
if (eventArgs.change === 'insert') {
eventArgs.items.forEach(function(addedElement) {
$.observe(addedElement, 'value1', function(e) {
var element = e.target;
element.value2 = 'Value1 is ' + element.value1;
$.observable(element).setProperty('value2', element.value2);
$.observable(model).setProperty('recent', element.value1);
});
});
}
});
});
});
html:
<div id="container"></div>
<script id="tmpl" type="text/x-jsrender">
<input id="addElement" type="button" value="add new element"/>
<div id="box">
{^{for elements tmpl="#elementTmpl"/}}
</div>
<input type="text" data-link="recent" />
</script>
<script id="elementTmpl" type="text/x-jsrender">
<div>
<input name="input1" data-link="value1" />
<input name="input2" data-link="value2" />
</div>
</script>
I created jsfiddle that illustrates the problem.
You can use ObserveAll(): http://www.jsviews.com/#observeAll.
Every time the element.value1 changes, you update the calculated properties element.value2 and model.recent.
I updated your fiddle here https://jsfiddle.net/1rjgh2sn/2/ with the following:
$.templates('#tmpl').link('#container', model)
.on('click', '#addElement', function () {
$.observable(model.elements).insert({});
});
$.observable(model).observeAll(function(e, eventArgs) {
if (eventArgs.change === "set" && eventArgs.path === "value1") {
var element = e.target;
$.observable(element).setProperty('value2', 'Value1 is ' + element.value1);
$.observable(model).setProperty('recent', element.value1);
}
});
i want to add element to div in angularjs. so write this code but not work correctly. thanks for your help :)
function TestController($scope) {
$scope.addElement = function(){
var myElements = angular.element(document.querySelector('#form'));
console.log(myElements);
if(myElements.length == 0)
alert("Not Find");
else
myElements.prepend( myElements[0].children[1]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController" id="form">
<input type="button" ng-click="addElement()" value="add"></input>
<div id="div">
<input type="text" name="name">
</div>
</div>
Here is what I have tried.
$scope.addElement = function(){
var myElements = angular.element(document.querySelector('#form'));
console.log(myElements)
console.log(myElements[0].children[1])
if(myElements.length == 0)
alert("Not Find");
else{
html = angular.element(myElements[0].children[1]).clone();
myElements.append( html);
}
You should use angular clone method.
EDIT.
Here it the Plunker
If I understood your question correctly, you want to append an input element to div on each ng-click?
You just need to target the div with jquery and append the element with it.
See example: http://jsbin.com/seyawemijo/edit?html,js,output
Often than not when you want to modify the DOM directly, there is a way to do it without.
"Thinking in Angular way"
function TestController($scope) {
$scope.textArr = [];
var count = 1;
$scope.addElement = function() {
var ele = {
model: 'hello ' + count++
}
$scope.textArr.push(ele);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="TestController" id="form">
<input type="button" ng-click="addElement()" value="add" />
<div ng-repeat="text in textArr">
<input type="text" ng-model="text.model">
</div>
<div>{{textArr}}</div>
</div>
Try this one
myElements.prepend(myElements[0].children[1].value);
I have altered the above solution to add other attributes(including id) to the input text element
var globalCntr = 0;
function TestController($scope) {
$scope.addElement = function() {
globalCntr ++;
$('<input>',{
type:'text',
id:('inputText'+globalCntr)
}).appendTo($('#target'));
};
}