how to get a value based on a selection in knockoutjs - javascript

I'm using knockout to get some data from an API to fill my textboxes. I want to get the unit price from the API when you select a drug. How can I do this?
<div class="control-group">
<label class="control-label">Drug:</label>
<div class="form-horizontal">
<select id="Drug_ddl" data-bind="options: drugs, optionsText: function (item) { return item.Description; }, value: selectedDrug" class="input-xlarge"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">Unit Price:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: unitPrice" step="0.01" class="input-xlarge" id="UnitPrice_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Quantity:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: quantity" step="1" class="input-xlarge" id="Qty_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Cost:</label>
<div class="form-horizontal">
<input type="text" data-bind="value: drugcost" readonly="readonly" step="0.01" class="input-xlarge" id="Cost_txt" />
<input type="button" id="AddDrugs_btn" data-bind="click: addDrug" class="btn btn-primary" value="Add" />
</div>
</div>
This is the code for the viewModel:
var claimEntryViewModel = function () {
var drugs = ko.observableArray([]);
var unitPrice = ko.observable('0.00');
var quantity = ko.observable('1');
var drugcost = ko.computed(function () {
return quantity() * unitPrice();
});
var loadDrugs = function () {
url = apiServerUrl + "Items/";
$.ajax({
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
contentType: 'application/json',
dataType: 'json',
type: 'GET',
crossDomain: true,
success: function (data) {
drugs(data);
},
error: function (data) {
console.log("Is not answered");
console.log(data);
}
});
}
var selectedDrug = ko.observable();
var addDrug = function () {
var match = ko.utils.arrayFirst(claimDrugs(), function (item) {
return selectedDrug().ID === item.Id;
});
if (!match) {
claimDrugs.push({
Id: selectedDrug().ID,
Description: selectedDrug().Description,
unitPrice: selectedDrug().SalesPrice,
quantity: quantity(),
drugcost: drugcost(),
});
} else {
errorMessage("Already exists!");
}
}
return {
drugs: drugs,
addDrug: addDrug,
selectedDrug: selectedDrug,
unitPrice: unitPrice,
quantity: quantity,
drugcost: drugcost,
}
}
someone kindly provide me with a code that can do this, i'm fairly new to knockout and don't really know how to go about this. thanks

super cool is right, subscribing is a good way to handle this.
selectedDrug.subscribe(function (newValue) {
neededInfo(getSelectedDrugInfoFromApi(newValue));
});
This will call the getSelectedDrugInfoFromApi() every time the selectedDrug observable value changes, and update the neededInfo observable.
Keep in mind not to update the selectedDrug value inside the subscribe function though, as it will create a loop.

Related

How to pass multiple input text value to method in controller

I having 3 textbox and I want to send value enter over there to controller method
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
#Html.ActionLink("Send", "MethodNameInController", "ColtrollerName", new { id= $('#id').val(),
id1= $('#id1').val(), id2= $('#id2').val()})
and in controller
public ActionResult MethodNameInController(int id, string id1, string id2)
{
//some text here
}
but it's sending null value
If you want to stay on the same view or redirect to another url after, instead of using #Html.ActionLink() try passing the values to the controller using an ajax call.
function submitAjax(){
//purely for readability
var id = $('#id').val();
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//ajax call
$.ajax({
url: "/ControllerName/MethodNameInController",
data: { id: id, id1: id1, id2: id2 },
success: function (result) {
//handle something here
}
});
};
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
<button type="button" onclick="submitAjax()">submit</button>
If the method does some processing and then returns you to a different view, you could do a form submit.
function submitForm(){
var $form = $("#idForm");
//optional validation
$form.submit();
};
<form id="idForm" class="form-horizontal" asp-controller="ControllerName" asp-action="MethodNameInController" >
<input class="form-control" type="text" id="id" name="id">
<input class="form-control" type="text" id="id1" name="id1">
<input class="form-control" type="text" id="id2" name="id2">
<!-- type="button" prevents the from from submitting so you can do validation checks in the js -->
<button type="button" onclick="submitForm()">submit</button>
</form>
I got the solution using ajax just want to know is there any direct solution
$(function () {
$('#receipt').unbind('click');
$('#receipt').on('click', function () {
$.ajax({
url: "/Controller/Method",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
fromDate: $("#fromDate").val(),
toDate: $("#toDate").val(),
id: $("#id").val()
}),
async: false
});
});
});

How to work that JavaScript_button in mustache template?

{{#stocks}}
<tr>
<td>{{client}}</td>
<td>{{productName}}</td>
<td>{{color}}</td>
<td>{{size}}</td>
<td>{{amount}}</td>
<td>
<form>
<div class="form-group">
<input type="text" id="addAmount" class="form-control">
</div>
<div style="display:none" class="form-group">
<input type="text" id="id" class="form-control" value="{{id}}" style="display:none">
</div>
</form>
</td>
<td>
<button type="button" class="btn btn-secondary" id="btn-addAmount">add</button>
</td>
</tr>
{{/stocks}}
this is my web_server project mustache template part
var addAmount = {
init: function () {
var _this = this;
$('#btn-addAmount').on('click', function () {
_this.addAmount();
})
},
addAmount: function () {
var data = {
id: $('#id').val(),
addAmount: $('#addAmount').val()
}
if(!data.addAmount) {
alert("input amount");
}
else {
$.ajax({
type: 'POST',
url: '/api/v1/addAmount',
dataType: 'json',
contentType: 'application/json; charset = utf-8',
data: JSON.stringify(data)
}).done(function() {
window.location.href = "/users/stock";
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
}
};
addAmount.init();
this is javascript button in my web_server project mustache template
When I run this code at this situation, only the first items button works. I want to make other buttons work too. Please tell me how to solve this problem.

How to create an object in this format

I'm trying to create an object to be sent in an AJAX request in the format I need.
In the code I'm able to get the name attribute for each input element and its value, but I need to create an object in the below format. How can I create that?
{
"userrole":"",
"userAttributes":{
"username":"alks",
"useraddress":"ajdaa",
"usercity":"lajsdk"
}
}
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
$(document).ready(function() {
$('#submit_data').on('click', function() {
$('.data-fields-container > .input-type').each(function() {
dataobj = {};
var attrkey = $(this).attr('data-attr-name');
var attrval = $(this).find('input').val();
})
$.ajax(function() {
url: "https://map.net/api/v44",
data: dataobj,
type: 'POST',
dataType: 'Json',
success: function(data) {
console.log('successful')
},
error: function(request, error) {
console.log('failed')
}
})
})
})
You could map the serializeArray() result and construct your object like:
$(document).ready(function() {
$('#submit_data').on('click', function() {
var dataobj = {userrole: $('[name="userrole"]').val()};
var attr = $('.data-fields-container input:not([name="userrole"])').serializeArray().map(function(o) {
this[o.name] = o.value;
return this;
}.bind({}))[0];
dataobj['userAttributes'] = attr;
console.log(dataobj);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
dataObj = {
"userrole":document.querySelector('div.input-type input[name="userrole"]').value,
"userAttributes":{
"username":document.querySelector('div.input-type input[name="username"]').value,
"useraddress":document.querySelector('div.input-type input[name="useraddress"]').value,
"usercity":document.querySelector('div.input-type input[name="usercity"]').value
}
}
You don't need to iterate through the inputs since your JSON format is static.

HTML radio button always submits last option to PHP

No matter what option is chosen, this code will always submit the second option to PHP.
Here is my form:
<div class="modal">
<div class="modalContent">
<div class="modalHeader">
<p>Add an income / expense</p>
<span class="closeBtn" onclick="closeit()">×</span>
</div>
<form class="insertData" action="insert.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="category">Category</label>
<select name="category" required>
<option value="food">Food</option>
<option value="bills">Bills</option>
<option value="rent">Rent</option>
</select>
<label for="amount">Amount</label>
<div class="radios">
<input type="radio" name="ie" value="income"><p>Income</p>
<input type="radio" name="ie" value="expense"><p>Expense</p>
</div>
<input type="number" name="amount" required>
<label for="description">Description (optional)</label>
<textarea type="text" name="description"></textarea>
<input id="start" type="text" name="start" value="" required style="display:none;">
<input id="end" type="text" name="end" value="" required style="display:none;">
<input class='submitBtn' type="submit" name="" value="Submit">
</form>
</div>
</div>
Here is the PHP (just echoing for debugging purposes right now):
if (isset($_POST['name'])) {
echo htmlspecialchars($_POST['ie']);
}
The data is going in via AJAX here (using FullCalendar)
select: function (start, end) {
document.getElementsByClassName('modal')[0].style.display = 'block';
document.getElementById('start').value = $.fullCalendar.formatDate(start,
"Y-MM-DD HH:mm:ss");
document.getElementById('end').value = $.fullCalendar.formatDate(end,
"Y-MM-DD HH:mm:ss");
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});
},
No matter what option is chosen it will always submit 'expense'.
If I swap them around on the form then it will always submit 'income', so it seems to be always the last option is being submitted.
This error occurs because you loop all element has name attribute, and get the value. Including radio button. If you want to get selected radio button you must add if, for check if radio button has checked.
You can use code below, this code simpleer then you must check radio button:
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
$.ajax({
url: url,
type: type,
data: $('form.insertData').serialize(),
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});

Posting data using AJAX while using knockout bindings

I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial

Categories

Resources