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>
Related
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;
});
<select ng-model="ad.Categorie"
ng-options="obj.id as obj.name for obj in categories"
ng-change="getSubcategories()"
class="form-control"
ng-required="true"
name="categorie">
<option value="">-- --</option>
</select>
When i submit getting ng-options array index instead of ad.Categorie value and i solved with hidden input
<input type="hidden" name="categorie" value="#{{ad.Categorie}}" />
but it seems wrong solution any idea?
var categories = [{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}];
reading from database. I want categories id as fk
public function store(Request $request)
{
$ad = new Ad;
$ad->categorie_id= $request->categorie;
$ad->subcategorie_id= $request->subcategorie;
$ad->type_id= $request->type;
$ad->location_id= $request->location;
$ad->title= $request->title;
$ad->description= $request->description;
$ad->price= $request->price;
$ad->phone= $request->phone;
$ad->code= $request->code;
//$ad->img = $request->file('img');
//$files = $request->file('img');
$ad->save();
return redirect('/');
}
is this array $request->categorie that's why i get index?
Your code is already getting right id, I am assuming you want to get object or index. this code is for getting index, id and object:
<select ng-model="ad.Categorie"
ng-options="obj.name for obj in categories"
ng-change="getSubcategories()"
class="form-control"
ng-required="true"
name="categorie">
</select>
In your controller:
function myCtrl($scope) {
$scope.categories = [{
"id": 11,
"name": "name1"
}, {
"id": 22,
"name": "name2"
}];
$scope.ad = {}
$scope.getSubcategories = function() {
console.log("selected object= ", $scope.ad.Categorie);
console.log("selected index= ", $scope.categories.indexOf($scope.ad.Categorie));
console.log("selected id= ",$scope.ad.Categorie.id);
}
}
Here is the working example:
https://jsfiddle.net/U3pVM/30048/
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"])