How to get values from dropdown box in MVC knockout binding - asp.net-mvc-3

This is hpw i'm filing my dropdown box
$.ajax({
url: "CheckinRelatedMember",
type: "POST",
data: { ClubId: localStorage.getItem("ClubId"), memacctno: localStorage.getItem("memacctno") },
async: false,
success: function (data) {
var RelatedMembers;
RelatedMembers = JSON.parse(data.CheckinRelatedMemberResult);
self.RelMembers(RelatedMembers);
How to get Option value from knockout dropdown list. I had successfully binded an dropdown box. but my problem is while i retrieve value from tag. option value unable to appear.
function FillCheckInRec() {
submemacctno = document.getElementById("RelateMem")[0].value;
i need to pass selected option value to FillCheckInRec() method.
<p>
<label>
Select Member
</label>
<select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionvalue:'AcctNo', value: 'AcctNo'"></select>
</p>
But while i pass select value into FillCheckinRec() method, value comes like this (""). how to get AcctNo From dropdown list. Please Help Me!

Try something like this
view:
<p>
<label>Select Member</label>
<select data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AccNo', value:AcctNo"></select>
</p>
<hr/>
<b><label data-bind="text:AcctNo"></label></b>
viewModel:
var ViewModel = function () {
var self = this;
self.RelMembers = ko.observableArray();
self.AcctNo = ko.observable();
$.ajax({
url: '/echo/json/',
type: "POST",
data: {},
success: function (data) {
var RelatedMembers = [{
'Name': 'One',
'AccNo': 1
}, {
'Name': 'Two',
'AccNo': 2
}, {
'Name': 'Three',
'AccNo': 3
}]
self.RelMembers(RelatedMembers);
}
});
};
ko.applyBindings(new ViewModel());
working sample here

Well I got fix this issue, Here is my code.
var submemacctno = $("#RelateMem").val();
<select id="RelateMem" class="input-medium" data-bind="options: RelMembers, optionsText:'Name',optionsValue:'AcctNo', value:'AcctNo'"></select>
This is my HTML Code, Rest of everything are same.
Thank You!

Related

Passing muliple options to controller in laravel

I'm trying to send multiple selected options to my controller but i can't
Code
route
Route::post('/spacssendto/{id}', 'ProductController#spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS: This form printed by Ajax in my view so it means there is several
more forms involved (the same way) that's why i mostly used classes
and not id's. Yet when I hit save button I will get 3 times repeat in
network (if i have 3 form)
Errors
Error 500 in network
dd result:
array:3 [
"_token" => "DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16"
"product_id" => "15"
"subspecification_id" => null
]
Question
How can I pass my multiple options (selected) to controller?
UPDATE
Thanks to Seva Kalashnikov I fixed the problem just for helping others I'll publish final results here so you can have full code, hope it helps.
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
You need to get select with css class subspecifications inside the same form element
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()
Try this code:
$('.sendspacsdatato').click(function() {
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': form.find('input[name=_token]').val(),
'product_id': id,
'subspecification_id': form.find('select.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});

DropDownList not populating with Data from Datasource

Hi I'm doing my first app mobile using telerik appBuilder and I can't get the Kendo datasource to work with a dropdown list.
The result of my webservices is below but I can't get the correct data-bind for that result.
{"d":[{"id":2209,"nom":"Test 1"},{"id":23608,"nom":"Test 2"},{"id":24061,"nom":"Test 3"},{"id":24741,"nom":"Test 4"},{"id":27347,"nom":"Test 5"}]}
Pls, any ideas? Thanks a lot.
/* product.html*/
<div id="product" data-role = "view"
data-layout = "sharedlayout" data-model="app.productService.viewModel">
<div class="view-content">
<form >
<div data-role="listview" data-style="inset">
<div>
Products:
<select id="product" data-role="dropdownlist"
data-bind="source: productsdataSource "
data-text-field="id"
data-value-field="product">
<option value="0"> </option>
</select>
</div>
</div>
</form>
</div>
</div>
ProductViewModel.js
(function (global)
{
var ProductsViewModel,
app = global.app = global.app || {};
ProductsViewModel = kendo.data.ObservableObject.extend (
{
getProducts: function() {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "urlexample",
type:"post",
contentType: "application/json; charset=utf-8",
dataType: "json"
}
},
schema: {
data: "d"
},
type: 'json'
});
}
});
app.productService = { viewModel: new ProductsViewModel() };
})(window);
I'm not sure exactly where your problem lies, but i've got a few ideas...
Why are you extending the observable? Why not just use kendo.observable({})?
Your viewModel is returning a function, not an object which is what Kendo UI would be expecting.
I think you might be over-complicating this slightly. I've put together a dead simple example...
http://plnkr.co/edit/T41nZqZNLqtOTfjG8upK?p=preview
Might I also suggest that you drop the data-role="dropdownlist"? Mobile devices have their own select list implementations and this way you can use the native select ability on the device.

How to programatically expand a node of Kendo treeview

I have a Kendo treeview that is built as below codes (see below). Each tree node has a unique data id field (that is employee Id).
I would like to have a text box ( <input type="text" ... /> ) and a button ( <input type="button" ... /> ) so user can input some id and when she hit the button, the button click event handler will let the treeview expand the node whose id matches the input id. How can I do that? Thank you very much.
Details of click event handler or the button:
function buttonExpand_onClick()
{
var id = $("textboxEmployeeId").val();
// ???
// how can I do the following code lines to expand the node with id of "id" to see all its children?
}
Details of the existing Kendo treeview building codes:
<div id="treeviewEmployee">
</div>
<script id="treeview-template" type="text/kendo-ui-template">
#: item.text #
</script>
$(function(
{
var defaultRootSelectedId = 1; // 1 is employee id of the root employee on first loading
$.ajax({
url: '/Employee/AjaxGetEmployeeNodes/?id=' + defaultRootSelectedId,
type: 'GET',
dataType: 'json',
async: false,
success: function (data, textStatus, xhr) {
$("#reeviewEmployee").kendoTreeView({
template: kendo.template($("#treeview-template").html()),
dataSource: data,
select: treeview_onSelect
});
_treeview = $("#treeviewEmployee").data("kendoTreeView");
},
error:
function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});
You can access the datasource on the treeview and find the node by id. I would also like to add that the treeView has a 'findByText()' method as well, in case that is what you want.
HTML
<script id="treeTemplate" type="text/x-kendo-template">
#: item.text #
</script>
<div id="content">
<div id="form">
<label>Node ID:
<input id="nodeId" type="text"/>
</label>
<button id="expandNodeBtn">Expand Node</button>
</div>
<h2>TreeView</h2>
<div id="treeView"/>
</div>
JAVASCRIPT
(function ($) {
$(document).ready(function () {
$("#treeView").kendoTreeView({
dataSource: [
{
text: 'one with id 1',
id: 1,
items: [
{
text: 'one-child-1',
id: 2
},
{
text: 'one-child-2',
id: 3
}
]
},
{
text: 'two with id 4',
id: 4,
items: [
{
text: 'two-child-1',
id: 5
},
{
text: 'two-child-2',
id: 6
}
]
}
]
});
$("#expandNodeBtn").on("click", function(e) {
var val = $("#nodeId").val();
console.log('val: ' + val);
var treeView = $("#treeView").data('kendoTreeView');
var dataSource = treeView.dataSource;
var dataItem = dataSource.get(val); // find item with id = 5
var node = treeView.findByUid(dataItem.uid);
treeView.expand(node);
});
});
})(jQuery);
JSFiddle
I also put together a JSFiddle sample for you to play with: http://jsfiddle.net/jsonsee/D35Q6/
Slightly related, but I came here looking for an answer to this question: How to expand the whole branch when clicking to a parent node in angular treeview? Since I didnt find any answers, I post my solution here. Hope it helps someone.
html
<div id="treeview" kendo-tree-view="tree" k-options="options" k-on-change="selectItem(dataItem)">
</div>
controller
$scope.options = {
dataSource: dummyData,
template: $scope.treeItemTemplate
}
$scope.treeItemTemplate = "<button ng-click='expandRoot(dataItem)'>Blow up</button>";
$scope.expandRoot = function expandRoot(dataItem) {
dataItem.expanded = true;
if (dataItem.hasChildren) {
dataItem.load()
var children = dataItem.children.data();
children.forEach(function (c) {
c.expanded = true;
$scope.expandRoot(c)
});
}
}

Best Way for Getting Value from a Clicked Checkbox, with JQuery

All,
Is this the best way to get the value of a currently-checked/unchecked checkbox?
The number of checkboxes is arbitrary so I need a way to get the value of the checkbox that was checked or unchecked.
By looking at Firebug, I see that by using:
this.defaultValue
I can get the value of the currently-checked/unchecked checkbox but not sure if that's really the best way.
Here is the HTML and below is the Javascript click handler
<div id="ClubSponsorshipPartial">
<table class="table-grid">
<tr>
<td>
<input type="checkbox" value="000000244187" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #1
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #2
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #3
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#ClubSponsorshipPartial input[type=checkbox]").click(function (e) {
var queryStr = '';
var clubKeyNumber = '';
var receivedBackgroundCheckChecked = false;
var memberId = this.defaultValue
clubKeyNumber = 'K06253';
receivedBackgroundCheckChecked = ($("#ClubSponsorshipPartial input[type=checkbox]").is(":checked") ? "true" : "false");
queryStr = "memberId=" + memberId + "&isChecked=" + receivedBackgroundCheckChecked;
$.ajax({
type: "POST",
url: '/Dashboard/BackgroundCheck',
data: queryStr,
datatype: 'json',
success: function (data) {
$.notification({
content: 'SLP Advisor Background Check status saved.',
error: false,
timeout: 5000
});
},
failure: function (data) {
$.notification({
content: 'Error saving SLP Advisor Background Check status.',
error: true,
timeout: 5000
});
},
timeout: 5000
});
});
});
</script>
the id should be unique in your page document, and you should use $(this) to mapping current DOM, you can try below code, may help;
http://jsfiddle.net/kJQr9/

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Resources