Cannot get value from select (JS) - javascript

I have Form with several selects
Here is code
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Ф.И.О</label>
<input type="text" class="form-control" id="Name">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Дата Рождения</label>
<input type="date" class="form-control" id="birthday">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Должность:</label>
<textarea class="form-control" id="position"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Телефон:</label>
<textarea class="form-control" id="telephonepeople"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">График работы:</label>
<select class="form-control" id="workTime">
<option>Дневная Смена</option>
<option>Ночная смена</option>
<option>Сутки</option>
<option>Дневная -Ночная смены</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Адрес проживания:</label>
<textarea class="form-control" id="adress"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Регион:</label>
#Html.DropDownList("Region", null, htmlAttributes: new { #class = "form-control", #id = "region" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Паспортные данные:</label>
<textarea class="form-control" id="passportData"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">ИНН:</label>
<textarea class="form-control" id="INN"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Медицинская книга:</label>
<select class="form-control" id="medicalCard">
<option>Имеется</option>
<option>Не Имеется</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Дата окончания мед книжки:</label>
<input type="date" class="form-control" id="bookending">
</div>
I need to get values from it and pass to back-end.
I have this javascript code (here is part, where I get values, because all other is working great)
function AddPeople() {
let proposalurl = '/peopleforworks/addpeople';
let Name = $('#Name').val();
let birthday = $('#birthday').val();
let telephone = $('#telephonepeople').val();
let workTime = $('#workTime').text();
let adress = $('#adress').val();
let passportData = $('#passportData').val();
let medicalCard = $('#medicalCard').val();
let INN = $('#INN').val();
let medicalbookdate = $('#bookending').val();
let position = $('#position').val();
let region = $('#region').text();
alert(workTime);
But alert shows me nothing. All other selects are working and values is getting from them.
Where can be my problem?
Thank's for help

You need to define a value for each of your select's <option>:
Replace this:
<select class="form-control" id="workTime">
<option>Дневная Смена</option>
<option>Ночная смена</option>
<option>Сутки</option>
<option>Дневная -Ночная смены</option>
</select>
By this:
<select class="form-control" id="workTime">
<option value="Дневная Смена">Дневная Смена</option>
<option value="Ночная смена">Ночная смена</option>
<option value="Сутки">Сутки</option>
<option value="Дневная -Ночная смены">Дневная -Ночная смены</option>
</select>
And also:
let workTime = $('#workTime').text();
By this:
let workTime = $('#workTime').val();

use .val()
let workTime = $('#workTime').val();

Related

data is not defined at HTMLButtonElement.GetADocument

I got this error where when I click the button from one row of my table
data is not defined at HTMLButtonElement.GetADocument
What I wanted to do was when button is click it will take the row id from firestore and display the details of the row in my form.
This is the function that needs to be executed after button is clicked:
async function GetADocument(){
var ref = doc(firestore, "ordered", data.id);
const docSnap = await getDoc(ref)
if(docSnap.exists()){
boxEmail.value = docSnap.data().paidby;
boxDate.value = docSnap.data().boughtAt;
boxName.value = docSnap.data().cetegory;
boxQty.value = docSnap.data().amount;
boxAddress.value = docSnap.data().paidby;
boxCode.value = docSnap.data().code;
boxEstimation.value = docSnap.data().estimationDate;
boxStatus.value = docSnap.data().status;
}
else{
alert('No Document found')
}
}
This is the row of table that contains the button that will get the id from the firestore:
const q = query(collection(firestore, "ordered"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
let id = doc.id;
let data = doc.data();
const list = document.getElementById("tbody1");
const row = document.createElement("tr");
row.innerHTML += `
<td class="grid-item">${(data.paidby)}</td>
<td class="grid-item">No. ${(data.numbur)}, Simpang ${(data.spg)}, Jalan ${(data.jln)}, ${(data.district)}, ${(data.code)}</td>
<td class="grid-item">${(data.product)} (${(data.amount)})</td>
<td class="grid-item">${(data.status)}</td>
<td class="grid-item">
<button type="button" id="viewDetail" class="btn btn-primary btn-primary my-2 ml-2" data-id="${id}">View Details</button>
</td>
`;
list.appendChild(row);
let detailView = document.getElementById('viewDetail');
detailView.addEventListener('click', GetADocument);
});
});
And, this is the form display:
<form>
<div class="form-group row">
<label for="emailBox" class="col-sm-2 col-form-label">User's Email</label>
<div class="col-sm-10">
<input type="email" readonly class="form-control" id="emailBox" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="form-group row">
<label for="dateBox" class="col-sm-2 col-form-label">Bought At</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="dateBox" placeholder="Bought Date">
</div>
</div>
<div class="form-group row">
<label for="nameBox" class="col-sm-2 col-form-label">Item Bought</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="nameBox" placeholder="Item Bought">
</div>
</div>
<div class="form-group row">
<label for="qtyBox" class="col-sm-2 col-form-label">Quantity</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="qtyBox" placeholder="Quantity">
</div>
</div>
<div class="form-group row">
<label for="addressBox" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="addressBox" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="codeBox" class="col-sm-2 col-form-label">Address Code</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="codeBox" placeholder="Address Code">
</div>
</div>
<div class="form-group row">
<label for="estimationBox" class="col-sm-2 col-form-label">Estimation Date</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="estimationBox" placeholder="Estimation Date">
</div>
</div>
<div class="form-group row">
<label for="statusBox" class="col-sm-2 col-form-label">Status</label>
<div class="col-sm-10">
<input type="text" readonly class="form-control" id="statusBox" placeholder="Status">
</div>
</div>
<button type="submit" class="btn btn-primary">Update Status to Delivered</button>
<button type="submit" class="btn btn-danger">Delete Record</button>
</form>
And how I declare the inputbox in the JavaScript is like this:
let boxEmail = document.getElementById('emailBox');
let boxDate = document.getElementById('dateBox');
let boxName = document.getElementById('namaeBox');
let boxQty = document.getElementById('qtyBox');
let boxAddress = document.getElementById('addressBox');
let boxCode = document.getElementById('codeBox');
let boxEstimation = document.getElementById('estimationBox');
let boxStatus = document.getElementById('statusBox');
I think there is something wrong in my id declaration, which is in the second coding data-id="${id}" and also how I have reference the data-id. Can someone please help me?

Why my equations are not running in this function?

Im having travel with te following function so when the value of tipoCompra == 'Nacional' the costUSD is going to be just the value of costUSD and disable the other fields, but if the value of tipoCompra == 'Exterior' the value of costUSD shall be auto completed with simple equations within other input fields.
function CalcularNacionalizacion(){
var tipoCompra = document.getElementById('tipoCompra').value;
var fob = document.getElementById('fob');
var nacFactor = document.getElementById('nacFactor');
var Nacionalizacion = document.getElementById('costNacionalizacion');
if (tipoCompra == 'Nacional'){
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
var totalUSD = document.getElemenById('costUSD').value;
} else {
fob.disabled = '';
nacFactor.disabled = '';
Nacionalizacion.disabled = '';
var fob = document.getElementById('fob').value;
var nacFactor = document.getElementById('nacFactor').value;
var Nacionalizacion = parseFloat(fob) * parseFloat(nacFactor);
document.getElementById('costNacionalizacion').value = Nacionalizacion;
var totalUSD = parseFloat(fob) + parseFloat(Nacionalizacion);
document.getElementById('costUSD').value = totalUSD;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" onchange="CalcularNacionalizacion();" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" class="form-control" required>
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" onchange="ToCalcularNacionalizaciondas();" onkeyup="CalcularNacionalizacion();" required>
</div>
If you choose the option 'Exterior' you can see that my equations are not running.
I do some refactoring in your code so that it would work
const tipoCompra = document.querySelector('#tipoCompra');
const fob = document.querySelector('#fob');
const nacFactor = document.querySelector('#nacFactor');
const Nacionalizacion = document.querySelector('#costNacionalizacion');
const costUSD = document.querySelector('#costUSD');
const elements = [tipoCompra, fob, nacFactor, Nacionalizacion, costUSD];
elements.forEach((i) => {
i.addEventListener('change', CalcularNacionalizacion);
});
function CalcularNacionalizacion(e) {
if (tipoCompra.value === 'Nacional') {
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
costUSD.value = costUSD.value;
} else {
fob.disabled = false;
nacFactor.disabled = false;
Nacionalizacion.disabled = false;
const fobValue = Number(fob.value);
const nacFacotrValue = Number(nacFactor.value);
const NacionalizacionValue = fobValue * nacFacotrValue;
Nacionalizacion.value = NacionalizacionValue;
const totalUSDValue = fobValue + NacionalizacionValue;
costUSD.value = totalUSDValue;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" required />
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" required />
</div>

Last-child not working inside iteration of div

In browser, the HTML is generated dynamically and is rendered as
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status0" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div><div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control"><option value="">Select Relationship</option><option value="Father">Father</option><option value="Mother">Mother</option><option value="Brother">Brother</option><option value="Sister">Sister</option><option value="Spouse">Spouse</option><option value="Guardian">Guardian</option></select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" placeholder="Name"></div><div class="col-sm-2"><input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" placeholder="Contact Number">
</div>
<button value="count-status1" class="remove-relationship-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
The code is
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName =$this.find("input[type=text]:first-child").val();
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
I am trying to fetch values of contact numbers i.e with id's relationship-type-contact(n) values in the line "
var relationshipContactNumber =$this.find("input[type=text]:last-child").val();"
This is fetching values of first-child textboxes in the variable relationshipContactNumber in the loop.
Please help !!!
This should work, use the .first() and .last() selectors.
Another way, if you have access to alter the HTML, is to add class names for the input fields and select them by using that instead.
function getData() {
var relationship_details_array = [];
// Relationship details Array
$(".relationship-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").each(function() {
var relationshipTypeValue = $(this).val();
var relationshipName = $this.find("input[type=text]").first().val();
var relationshipContactNumber = $this.find("input[type=text]").last().val();
var innerRelationshipArray = {};
innerRelationshipArray = {
relationshipTypeValue: relationshipTypeValue,
relationshipName: relationshipName,
relationshipContactNumber: relationshipContactNumber
};
relationship_details_array.push(innerRelationshipArray);
});
});
console.log(relationship_details_array);
}
$("#getData").on("click", getData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="getData">Show data in console log</button>
<div id="dynamic-relationship-details">
<div id="count-status0" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type0" class="form-control">
<option value="">Select Relationship</option>
<option value="Father">Father</option>
<option value="Mother" selected>Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name0" id="relationship-type-name0" class="form-control" value="Mommy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact0" id="relationship-type-contact0" class="form-control" value="1234" placeholder="Contact Number">
</div>
</div>
<div id="count-status1" class="relationship-container form-group">
<div class="col-sm-1"></div>
<div class="col-sm-2">
<select id="relationship-type1" class="form-control">
<option value="">Select Relationship</option>
<option value="Father" selected>Father</option>
<option value="Mother">Mother</option>
<option value="Brother">Brother</option>
<option value="Sister">Sister</option>
<option value="Spouse">Spouse</option>
<option value="Guardian">Guardian</option>
</select>
</div>
<div class="col-sm-3">
<input type="text" name="relationship-type-name1" id="relationship-type-name1" class="form-control" value="Daddy" placeholder="Name">
</div>
<div class="col-sm-2">
<input type="text" name="relationship-type-contact1" id="relationship-type-contact1" class="form-control" value="5678" placeholder="Contact Number">
</div>
</div>
</div>

Dynamically switch between field sets in html

I currently have a dropdown field that onchange will input the value.
function CurrentStatusChanged() {
var currentS1 = document.getElementById("currentStatus1").value;
var currentS2 = document.getElementById("currentStatus2").value;
document.getElementById("currentStatusView1").innerHTML = "You selected: " + currentS1;
document.getElementById("currentStatusView2").innerHTML = "You selected: " + currentS2;
}
I have many fieldsets created and then correct fieldset needs to show dependent on the what selected in the dropdown box.
My question is:
What is the best approach? As I don't feel innerHTML then all of the code is good practise.
<fieldset class="employed">
<h2>Employed</h2>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="partTime">If Part Time, please detail your contractual hours per week</label>
<div class="col-md-4">
<textarea class="form-control" id="partTime" name="partTime"></textarea>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="numberOfJobs">Number of Jobs</label>
<div class="col-md-4">
<input id="numberOfJobs" name="numberOfJobs" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobDescriptionTitle">Job Description / Title</label>
<div class="col-md-4">
<input id="jobDescriptionTitle" name="jobDescriptionTitle" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
I am trying to add a field set like the one above to a container, however i have at least 12 that change dependent on the drop-down. kindisch answer doesn't allow mt use the complete field set but is on the right track i believe.
Use templates for that. For example:
var storage = [],
select = document.getElementById("selection"),
container = document.getElementById("container");
select.addEventListener("change", function() {
var _id = select.value,
_tpl = document.getElementById(_id);
save();
container.innerHTML = _tpl.innerHTML;
update();
}, false);
// Save current state
function save() {
var _fields = container.getElementsByClassName("form-control");
for (var i = 0; i < _fields.length; i++) {
storage[_fields[i].name] = _fields[i].value;
}
}
// Fill input fields of element
function update() {
var _fields = container.getElementsByClassName("form-control");
for (var i = 0; i < _fields.length; i++) {
if (_fields[i].name in storage) {
_fields[i].value = storage[_fields[i].name];
}
}
}
<select id="selection">
<option value="status-one">One</option>
<option value="status-two">Two</option>
<option value="status-three">Three</option>
</select>
<div id="container"></div>
<script type="text/html" id="status-one">
<fieldset class="employed">
<h2>Employed</h2>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="partTime">If Part Time, please detail your contractual hours per week</label>
<div class="col-md-4">
<textarea class="form-control" id="partTime" name="partTime"></textarea>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="numberOfJobs">Number of Jobs</label>
<div class="col-md-4">
<input id="numberOfJobs" name="numberOfJobs" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobDescriptionTitle">Job Description / Title</label>
<div class="col-md-4">
<input id="jobDescriptionTitle" name="jobDescriptionTitle" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
</script>
<script type="text/html" id="status-two">
<p>This is status two.</p>
</script>
<script type="text/html" id="status-three">
<p>This is status three.</p>
</script>
could you use html5 data attributes? https://jsfiddle.net/hj6bbgbd/
<select id="mySelect" onchange="myFunction()">
<option value="1" data-text = "text for choice one">One</option>
<option value="2" data-text = "text for choice two">Two</option>
<option value="3" data-text = "text for choice three">Three</option>
</select>
<fieldset>
<fieldset>
<legend>My Legend:</legend>
<p id="demo"> text for choice one </p>
</fieldset>
<script>
function myFunction() {
var sel = document.getElementById('mySelect');
var opt = sel.options[sel.selectedIndex];
document.getElementById("demo").innerHTML = opt.dataset.text;
}
</script>

Unable to create array of object to save MongoDB from AngularJS

I have created html dynamically and want to save in MongoDB using Mongoose from AngularJS. But the problem is that, I'm unable to create that require object which I have created Mongoose schema.
model code
var SegmentSchema = new Schema({
name: String,
uiName:String,
type:String,
lower:Number,
upper:Number,
options:[{key:String,value:String}]
});
export default mongoose.model('Segment', SegmentSchema);
view code
<form class="form-horizontal" ng-submit="addSegment()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<p class="form-control-static"><input class="form-control" type="text" required ng-model="segment.name" name="name" value=""></p>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">UI Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" ng-model="segment.uiName" name="uiName" value="">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">Type</label>
<div class="col-sm-6">
<select ng-model="segment.type" ng-change="changeType()" class="form-control" name="type">
<option value="">---select type---</option>
<option value="text">Text</option>
<option value="range">Range</option>
<option value="select">Select</option>
<option value="binary">Binary</option>
</select>
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.lower" type="number" name="lower" value="">
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.upper" type="number" name="upper" value="">
</div>
</div>
<div ng-show="numOptionShow" class="form-group">
<label for="inputPassword" class="col-sm-6 control-label"></label>
<div class="col-sm-2">
<input placeholder="Options count" class="form-control col-sm-3" ng-keydown="keyupOptionNumber()" ng-keyup="keyupOptionNumber()" ng-model="numOption" type="text" value="">
</div>
</div>
<div ng-show="selectOptionShow" class="" id="segment-select-option">
</div>
<div class="form-group">
<button type="submit" ng-show="addSegmentBtn" class="btn btn-success">Add</button>
</div>
</form>
angularjs(controller) code:
angular.module('nrichApp')
.controller('SegmentCtrl', function ($scope,$http,segment) {
$scope.loading = true;
$scope.addSegmentDiv=false;
segment.get().success(function(data) {
$scope.segments=data;
});
$scope.loading = false;
})
.controller('AddSegmentCtrl', function ($scope,segment,$location,$compile) {
$scope.loading = true;
$scope.addSegmentBtn=false;
$scope.changeType=function(){
$scope.addSegmentBtn=true;
$scope.rangeShow=false;
$scope.selectOptionShow=false;
$scope.numOptionShow=false;
switch ($scope.segment.type) {
case 'range':
$scope.rangeShow=true;
break;
case 'select':
$scope.numOptionShow=true;
break;
case 'binary':
break;
default:
}
};
$scope.keyupOptionNumber=function(){
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
$scope.addSegment=function(){
$scope.loading = true;
var param = {'segment' : $scope.segment};
console.log(JSON.stringify(param));//it is output which show at below
segment.create(param)
.success(function(data) {
$scope.loading = false;
$location.path('/segment');
});
$scope.loading = false;
};
});
Output:
{
"segment":{
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options":{
"0": { "key":"k3","value":"v2"},
"1": { "key":"k4","value":"v4"}
}
}
}
Desired Output:
{
"segment": {
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options": [
{"key":"k3","value":"v2"},
{"key":"k4","value":"v4"}
]
}
}
Finally, i got solution. I just declare array data type for options variable i.e,
$scope.options=[]
Inside angular controller:
$scope.keyupOptionNumber=function(){
$scope.options=[];//Here, this line is missing
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
Thanks #shaishab roy

Categories