Textchanged event in mvc for a Textbox - asp.net-mvc-4

I am a beginer in mvc.I am working on an application where i need to change the value of a textbox after i enter a value in it and press TAB.For example when i enter 1 in textbox and press tab it should display +1 ie i need to concatinate a + sign to the text i enter.SO to do this i am trying to raise a textchanged event for the textbox.How can i do it.When i googled it i found that it can be done using javascript.But i dont know how to do that,pls give me some suggessions.
Code:
#Html.TextBoxFor(m => m.text)--textbox

You could use jQuery and subscribe to the blur event which will be triggered when the input field looses focus:
$(function() {
$('#id_of_your_textbox').blur(function() {
var value = $(this).val();
var newValue = value + '1';
$(this).val(newValue);
});
});
If you don't want to use a javascript framework such as jQuery you could achieve the same with plain javascript:
window.onload = function() {
document.getElementById('id_of_your_textbox').onblur = function() {
var value = this.value;
var newValue = value + '1';
this.value = newValue;
};
};
Note: this will add the string value 1 to the existing text. If you wanted to perform an integer addition you need to parse the current value first. You could use the parseInt or parseFloat methods (depending on the data type) for that:
var value = parseInt($(this).val());
if (!isNaN(value)) {
var newValue = value + 1;
$(this).val(newValue);
} else {
alert('You have entered an invalid integer value');
}
And here's how to assign a deterministic id to your text field that you could use in your javascript selectors:
#Html.TextBoxFor(m => m.text, new { id = "id_of_your_textbox" })

Related

Data table on click on dynamic controls

I have a jquery data table that I am populating from a drop down on change event. I have two check boxes in the data table and I am running an onclick on the check boxes. But on the first click the jquery does not fire only when I click it a second time does the jquery fire, also happens on switching pages.I added the .on() for the click, because I researched and saw that dynamic controls would work that way. Is there something I'm missing also to get this click function to work on first click? Below is some of my code.
data table click on check box control no jquery click event on first click
data table click on check box control on second click
$('#my-table').on('click', function () {
var i = -1;
$("input[id*='secondary']:checkbox").on("click", function () {
if ($(this).is(':checked')) {
i = selectedIds.indexOf($(this).val());
if (i === -1) {
selectedIds.push($(this).val());
}
CheckedSecondary(this);
}
else {
jQuery(this).closest("tr").css("background-color", "");
if (selectedIds.length > 0) {
i = selectedIds.indexOf($(this).val());
if (i != -1) {
selectedIds.splice(i, 1);
}
}
if (!primaryChecked)
$(this).closest('tr').find('input[type="checkbox"]').not(this).attr('disabled', false);
}
});
$("#my-table").find("input[id*='primary']:checkbox").on("click", function () {
if ($(this).is(':checked')) {
primaryChecked = true;
primaryID = this.value;
CheckedPrimary(this);
}
else {
primaryID = "";
primaryChecked = false;
$(this).closest('tr').find('input[type="checkbox"]').not(this).attr('disabled', false);
$('input:checkbox[id^="primary"]').each(function () {
if (!$(this).closest('tr').find('input[type="checkbox"]').is(':checked'))
$(this).attr('disabled', false);
});
jQuery(this).closest("tr").css("background-color", "");
}
});
});
You're attaching click handler inside another click handler which doesn't make sense.
Remove first click handler:
$('#my-table').on('click', function () {
});
Attach the click handler to the checkboxes as follows:
$('#my-table').on('click', "input[id*='secondary']:checkbox", function () {
});
and
$('#my-table').on('click', "input[id*='primary']:checkbox", function () {
});

How to set cell value in DataTable on button click

I'm trying to modify a cell value using DataTable (the new version) when an outside button is clicked.
I have the following for now:
$(document).on('click', '.dropdown-menu li a', function () {
if ($(this).text() == "development") {
var cell = table.row( 6 ).data()[4]
cell.data( "development" ).draw();
}
});
This doesn't work since I think the table row and data retrieval method doesn't return an object with .data() attribute that allows me to set data cell value. I'm getting the following error: cell.data is not a function. (In 'cell.data( "development" )', 'cell.data' is undefined)However, I'm not sure how to access a table cell value the .data() way without having a click even in the table. My button is placed outside the table somewhere else.
Any idea how to make this work?
Since DataTables 1.10+ might not support fnGetNodes() as mentioned on the API landing page itself, instead now you can use rows().nodes().
Example: http://jsfiddle.net/cmedina/7kfmyw6x/28/
var table = $('#example').DataTable({sorting : false});
var row = table.row(0).node();
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
table.cell(row, 0).data('Development').draw();
}
});
If you work with DataTables < 1.10 then you can use fnUpdate
Example: http://jsfiddle.net/cmedina/7kfmyw6x/29/
var oTable = $('#example').dataTable({sorting:false});
$('#test').on( 'click', function () {
var text = "development";
if (text == "development") {
oTable.fnUpdate('Development', 0, 0 ); // Single cell
}
})
you can use fnUpdate Datatables Function to update any specific cells just by row and col indexes.
something like this :
var oTable = $('#example').dataTable();
$('#button').click(function() {
var row = document.getElementById("indexDepRow").value;
var col = document.getElementById("indexDepCol").value;
oTable.fnUpdate('development', parseInt(row), parseInt(col));
});
See JsFiddle EXAMPLE

Get data object on row click

I am using jquery datatables and I am having trouble grabbing the row data on click event. How can I get my data object from my datatable on row click event?
What I do:
jquery post to get a json response load json response as data into datatable (array of objects)
jquery, register click event on
datatable rows when user clicks on row, need to get data object for
row clicked on
My current code:
function contactSearchListTable(data) {
// data is array of javascript object
console.log('contactSearchListTable()');
$(contactSearchResultsTableElement + ' tbody').off();
if ( $.fn.dataTable.isDataTable(contactSearchResultsTableElement) ) {
$(contactSearchResultsTableElement).DataTable().destroy();
}
if (data.length == 0) {
$(contactSearchResultsTableElement).html('');
}
var table = $(contactSearchResultsTableElement);
var params = {"data":data
,"info": false
,"searching": false
,"ordering": false
,"lengthChange": false
,"columns":[
{"data":"id","visible":false}
,{"data":"name","title":"Name","class":"clickable"}
,{"data":"phoneHome","title":"Home","class":"clickable"}
,{"data":"phoneWork","title":"Work","class":"clickable"}
]
};
var dt = table.dataTable(params);
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function () {
console.log(this); // <tr> html from datatable
// **** need to get hidden ID value here, HOW?
} );
}
You can access the data using row().data() function, change you click handler to:
$(contactSearchResultsTableElement + ' tbody').on('click', 'tr', function (){
var data = dt.api().row(this).data();
});

Mvc and konckout: click data bind won't redirect to another action

I want to have in foreach loop list of a href labels with links to MyAction.
In Edit.cshtml (http://localhost/mysite/Order/Edit/4) in foreach loop (knockout) I have a href for each item:
Eddit
Method is implemented in ViewModel.js:
self.EditForStore = function (item) {
console.log(item.IdStore());
var idStore = item.IdStore();
//var urlMeta = '#Url.Action("MyAction", "MyController", new { pStoreId = ' + idStore.toString() + ' })';
var urlMeta = '#Url.Action("MyAction", "MyController", new { pStoreId = 4 })';
//var myURL = '#Url.Action("MyAction", "MyController")';
window.location.href = urlMeta;
};
I cannot redirect to MyAction.
When I set location.href , it redirect to http address:
http://localhost/mysite/Order/Edit/4/MyAction/MyController?pStoreId=4
I cannot change the location.href, I only appends text to my current address.
A technique I have used for getting server side routes into knockout is to generate the route with a known parameter value and store it as a data attribute. Then knockout then pushes the data value into the href.
You can take advantage of the $element context variable to supply the current element into a function declared on the parent viewModel in a foreach binding, the use the attr binding to update the href attribute.
For example...
HTML
<div data-bind="foreach: stores">
</div>
Javascript
var ViewModel = (function() {
var ctor = function ViewModel() {
this.stores = ko.observableArray( [{ id: 1 }, {id:2}, {id:3}, {id:4} ]);
};
ctor.prototype.buildUrl = function(element, data) {
return element.getAttribute('data-url').replace('pStoreId=0', 'pStoreId=' + data);
};
return ctor;
})();
ko.applyBindings( new ViewModel() );
See http://jsfiddle.net/9Lz4493d/ for a sample (without the razor syntax and a hard coded data-url attribute, but you get the idea.)
The Url builder function could easily be enhanced to supply the parameter name, etc.

Can we implement On key up filter option in Yii's cGridview?

I am currently trying to implement automatic filtering in Yii cGridview, By default it filters 'onclick', or 'enter' key press, But I need to change that event to "onkeyup"|
my code is like this
Yii::app()->clientScript->registerScript('search',"
$('.filters > td >input').keyup(function(){
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
when I entered the first letter filtering occured, but after filtering and rendering the code fails.. please give me a solution.. Is there any php yii gridview extension which has filtering onkeyup
You need to change the way you attach the keyup listeners. After the gridview refreshed through AJAX, all elements inside the grid are replaced. So there's no keyup attached anymore. You can try something like:
$('body').on('keyup','.filters > td > input', function() {
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
#Michael Härtl's answer is right. But 2 Problem occur when you use this code.
1) When User Search in filter at that time, every time grid will be refresh so focus of input box will be lost.
2) When you search in one filter input and if you go to second input field field at that time first input box will be lost.
So now I have got the solution for that.
Set this java script code on your grid view.
Yii::app()->clientScript->registerScript('search', "
$('body').on('keyup','.filters > td > input', function() {
$(document).data('GridId-lastFocused',this.name);
data = $('#GridId input').serialize();
$('#GridId').yiiGridView('update', {
data: data
});
return false;
});
// Configure all GridViews in the page
$(function(){
setupGridView();
});
// Setup the filter(s) controls
function setupGridView(grid)
{
if(grid==null)
grid = '.grid-view tr.filters';
// Default handler for filter change event
$('input,select', grid).change(function() {
var grid = $(this).closest('.grid-view');
$(document).data(grid.attr('id')+'-lastFocused', this.name);
});
}
// Default handler for beforeAjaxUpdate event
function afterAjaxUpdate(id, options)
{
var grid = $('#'+id);
var lf = $(document).data(grid.attr('id')+'-lastFocused');
// If the function was not activated
if(lf == null) return;
// Get the control
fe = $('[name=\"'+lf+'\"]', grid);
// If the control exists..
if(fe!=null)
{
if(fe.get(0).tagName == 'INPUT' && fe.attr('type') == 'text')
// Focus and place the cursor at the end
fe.cursorEnd();
else
// Just focus
fe.focus();
}
// Setup the new filter controls
setupGridView(grid);
}
// Place the cursor at the end of the text field
jQuery.fn.cursorEnd = function()
{
return this.each(function(){
if(this.setSelectionRange)
{
this.focus();
this.setSelectionRange(this.value.length,this.value.length);
}
else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', this.value.length);
range.moveStart('character', this.value.length);
range.select();
}
return false;
});
}");
Add this line to your gridview widget code.
'afterAjaxUpdate'=>'afterAjaxUpdate',
For example:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'GridId',
'afterAjaxUpdate'=>'afterAjaxUpdate',
));