I have these:
<input class="orders" name="orders[]" value="1">
<input class="orders" name="orders[]" value="2">
<input class="orders" name="orders[]" value="3">
I try add values of orders to an serializeArray in JQUERY.
I do this:
var datastring = $("#form1").serializeArray();
var orders = [];
$('input.orders').each(function() {
orders.push($(this).val());
});
datastring.push({name: "orders", value: orders});
in server side,(when I convert it into a json format) I want ["1","2","3"]
but now only I get a string:1,2,3
I try change it to:
datastring.push({name: "orders[]", value: orders});
Now when I convert it to json string (in server side) I get this:
["1,2,3"]
can please tell me my mistake?
What you want is an array with objects that have the same name
var datastring = $("#form1").serializeArray();
$('input.orders').each(function() {
datastring.push({name: this.name, value: this.value});
});
And make you sure you use the correct class, remove the brackets
<input class="orders" name="orders[]" value="1">
<input class="orders" name="orders[]" value="2">
<input class="orders" name="orders[]" value="3">
This will give you an array looking like
[
{
"name": "orders[]",
"value": "1"
},
{
"name": "orders[]",
"value": "2"
},
{
"name": "orders[]",
"value": "3"
}
]
jQuery will in turn parse that array to the string orders[]=1&orders[]=2&orders[]=3 when submitted, which is what most serverside languages that parse [] as form groups expect, both the key and the value for each element.
Just try joining the array:
Example snippet for reference:
var datastring = [];
datastring.push({
name: "orders",
value: ['1', '2', '3'].join(',')
});
console.log(datastring[0]["value"])
Related
I am trying to achieve the following dynamic JSON string creation. I can produce the id part but don't how to produce the name part. Ids are from the list and name is from the textbox.
I tried a lot but nothing seems to work. I want to select both strings and text box should result as below.
{
"name": "GROUP-X1",
"objects": [{ // this part is needed as a complete string
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589948757"
}, {
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589945523"
}]
}
var output = createJSON1();
function createJSON1() {
var arr = $("#select1 > option").map((index, val) => ({
"type": "Host",
id: val.value
})).get();
return JSON.stringify(arr);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
Your code already builds the objects array. As such, all you need to do is wrap the output within another object providing the name property which you can retrieve from the value of #srch-obj. Try this:
var output = createJSON1();
function createJSON1() {
let obj = {
name: $('#srch-obj').val(),
objects: $("#select1 > option").map((t, el) => ({
type: "Host",
id: el.value
})).get()
}
return JSON.stringify(obj);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
I am using an ng-repeat to repeat through questions provided by an ajax response and I need the ng-model of each question input to point to a separate answers array.
The question array looks like this
bookingQuestions: [
0: {
label: 'Any allergies?',
type: 'text',
id: 1234
},
1: {
label: 'Names of attendees',
type: 'text',
id: 1235
}
]
I create the answers array by looping through all the questions and pushing the id and an empty answerValue property into my empty bookingAnswers array. The answers array looks like this:
bookingAnswers: [
0: {
id: 1234,
answerValue: ''
},
1: {
id: 1235,
answerValue: ''
}
]
In the markup, I'm attempting to init the answerObj by getting the correct answer object to match the corresponding question.
<div class="question" ng-repeat="question in bookingQuestions">
<label class="question-label" for="{{question.id}}">{{question.label}}
</label>
<input type="text" name="{{question.id}}" ng-model="answerObj"
ng-init="answerObj = getAnswerObj(question)">
</div>
The JS function:
$scope.getAnswerObj = function(question) {
angular.forEach(bookingAnswers, function(answer) {
if(question.id === answer.id) {
return answer.answerValue;
}
});
}
Even though the JS function successfully returns the correct object property, the ng-model isn't being updated to use it. How do I get this working?
You bind the ng-model of all your inputs to some answerObj meaning they all point to the same variable. Using $index you can access the index of the current iteration. So you could do something like this:
<input type=“text“ name="{{question.id}}"
ng-model="bookingAnswers[$index].answerValue"> </div>
<div class="question" ng-repeat="question in bookingQuestions">
<label class="question-label" for="{{question.id}}">{{question.label}}
</label>
̶<̶i̶n̶p̶u̶t̶ ̶t̶y̶p̶e̶=̶"̶t̶e̶x̶t̶"̶ ̶n̶a̶m̶e̶=̶"̶{̶{̶q̶u̶e̶s̶t̶i̶o̶n̶.̶i̶d̶}̶}̶"̶ ̶n̶g̶-̶m̶o̶d̶e̶l̶=̶"̶a̶n̶s̶w̶e̶r̶O̶b̶j̶"̶
<input type="text" name="{{question.id}}" ng-model="answerObj.answerValue"
ng-init="answerObj = getAnswerObj(question)" />
</div>
$scope.getAnswerObj = function(question) {
angular.forEach(bookingAnswers, function(answer) {
if(question.id === answer.id) {
̶r̶e̶t̶u̶r̶n̶ ̶a̶n̶s̶w̶e̶r̶.̶a̶n̶s̶w̶e̶r̶V̶a̶l̶u̶e̶;̶
return answer;
}
});
}
I have the code below, which I use to type and suggest a few relation names in an input field. The data variable right now returns only names like:
var data = ["name": "Relation 1", "name":"Relation 2"]
I modified it and now it has data like:
var data = [
{"id":1,"name":"Foo"},
{"id":2,"name":"Bar"},
{"id":3,"name":"Foo Bar"}
];
How do I append the id of the selected name in the id input?
$('input.relation').typeahead({
source: function (query, process) {
return $.get('live_search.php?filter=relation', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
return process(data);
});
}
});
<div class="form-group">
<label for="relation"> Relation </label>
<input class="relation form-control" type="text">
<input class="relation-id form-control" type="text" name="id">
</div>
I need send a json via post to api in this format:
"answer" => {
"name"=>"Test",
"email"=>"test#test.com",
"hospital"=>"Hospital Name",
"answered_questions_attributes"=>{
"0"=>{
"value"=>"1",
"question_id"=>"1"
},
"1"=>{
"value"=>"0",
"question_id"=>"2"
},
"2"=>{
"value"=>"1",
"question_id"=>"3"
}
}
}
I get the "answered_questions_attributes" data from inputs, the values are true or false and the name of the input is the question ID, eg:
<div class="resp_val_div">
<input type="hidden" name="1" value="1" />
<input type="hidden" name="2" value="0" />
<input type="hidden" name="3" value="1" />
</div>
I tried the code below, but this only returns a incorrect json:
var resp_val = jQuery(".resp_val_div").find("input");
var dados = {
"name": jQuery("#name").val(),
"email": jQuery("#email").val(),
"hospital": jQuery(".answer_hospital").val(),
'answered_questions_attributes':[]
};
resp_val.each(function(index, el) {
d = {"value":parseInt(el.value), "question_id":el.name};
dados.answered_questions_attributes.push(d);
});
console.log(dados);
"answer"=>{
"name"=>"Test",
"email"=>"test#test.com",
"hospital"=>"Hospital Test",
"answered_questions_attributes"=>[
{
"value"=>1,
"question_id"=>"1"
},
{
"value"=>0,
"question_id"=>"2"
},
{
"value"=>1,
"question_id"=>"3"
}
]
}
How can i create the first json in this case?
Don't use an array and .push() if you want an object. And don't use parseInt() if you want the value property to be a string rather than a number.
var dados = {
"name": jQuery("#name").val(),
"email": jQuery("#email").val(),
"hospital": jQuery(".answer_hospital").val(),
'answered_questions_attributes':{}
};
resp_val.each(function(index, el) {
d = {"value":el.value, "question_id":el.name};
dados.answered_questions_attributes[index] = d;
});
can you see what i'm trying to do here? I want to push some objects into a variable but keep it all tidy and contained.
var toggles = document.querySelectorAll('[data-search-toggle]').forEach(function(el) {
this.push({ 'element': el, 'select': el.dataset });
});
Obviously the code above doesn't work, that's just the concept of what I want, so if I was to console.log toggles below this I would get along the lines of:
[
{
'element': [Object],
'select': 'dropdown-search__select--make'
},
{
'element': [Object],
'select': 'dropdown-search__select--make'
},
{
'element': [Object],
'select': 'dropdown-search__select--make'
},
]
Edit:
Or would I need to do something like this:
var tmp;
var toggles = document.querySelectorAll('[data-search-toggle]').forEach(
tmp.push(function(el) {
return { 'element': el, 'select': el.dataset };
})
);
HTML:
<input type="radio" class="dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--cars" value="cars" checked required data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--cars">Cars</label>
<input type="radio" class="dropdown-search__radio dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--vans" value="vans" data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--vans">Vans</label>
<input type="radio" class="dropdown-search__radio dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--bikes" value="bikes" data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--bikes">Bikes</label>
You can convert the result of querySelectorAll to an array with the Array.from function and pass a map function as the second argument to wrap each of the elements in an object.
const toggles = Array.from(document.querySelectorAll('[data-search-toggle]'), (el) => {
return {
element: el,
select: el.dataset
};
});
console.log(toggles);
<input type="radio" class="dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--cars" value="cars" checked required data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--cars">Cars</label>
<input type="radio" class="dropdown-search__radio dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--vans" value="vans" data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--vans">Vans</label>
<input type="radio" class="dropdown-search__radio dropdown-search__radio" name="vehtype" id="dropdown-search__vehtype--bikes" value="bikes" data-search-toggle="dropdown-search__select--make">
<label class="dropdown-search__label--radio" for="dropdown-search__vehtype--bikes">Bikes</label>
You can use spread element to convert NodeList to an Array, .map() to return an object for each element of array. To get the .dataset where property contains - characters between word characters, camel case the property reference
var toggles = [...document.querySelectorAll("[data-search-toggle]")].map(el =>
({ "element": el, "select": el.dataset.searchToggle })
});