jquery mobile listview search filter start typing detect - jquery-mobile

I want to detect when a user start type intp jquery mobile list view filter input.
Also get which buttons user type.
<ul data-role="listview" data-filter="true">
<li>Acura</li>
<li>Audi</li>
<li>BMW</li>
</ul>
Any help would appreciated.
Note : This is a PhoneGap app.

Found how to do it. Im posting it if anyone have same question.
$('div.ui-input-search').delegate("input", "keyup",
function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code != 8) {
//Any key other that backspace clicked
var text = $(this).val();
if (text.length == 1) {
//Just Started Typing
}
}
}
);
$('div.ui-input-search').delegate("input", "keydown",
function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 8) {
// BackSpace is clicked.
var remainingText = $(this).val();
if (remainingText.length == 1) {
//Cleared all characteres
}
}
// console.log(code+'\n\n\n');
// var remainingText = $(this).val();
// console.log(remainingText);
}
);

Related

Converting an #Html.Textbox button to submit button

I am trying to convert an #Html.Textbox image button to submit button with the onclick calling a Javascript function but I can't seem to figure out the validation part. I believe it does need to be a submit button.
I am basically trying to get rid of the image but keep the functionality.
Here's what's working today.
#Html.TextBox("Next", null, new {type = "image", src = #Url.Content("../App_Themes/icons/button_next.png"), #class = "imgbottom", onclick = "javascript: ValidateSelection ($(\"[name$='selectedItems']:checked\"))"})
function ValidateSelection(item) {
if (item == null || item.length == 0) {
var validationSummary = $('.validation-summary-errors ul');
if (validationSummary.length > 0 && $('.validation-summary-errors ul li').length == 0) {
validationSummary.append('<li>' + "Please select at least one item" + '</li>');
}
var errors = $("[name='ErrorMessage']");
if (errors.length > 0) {
errors.hide();
}
var buttonGenerateReport = $("#GenerateReport");
if (buttonGenerateReport.length > 0) {
buttonGenerateReport.hide();
}
event.preventDefault();
}
}
<button type="submit" class="imgbottom" onclick="ValidateSelection('selectedItems');">
<img src="#Url.Content("~/App_Themes/icons/button_next.png")" alt="Next" /><br />
Next
</button>
The "~/" part of the Url Content string represents your project root, so adjust it to fit your correct file address later.
Or you could just use FontAwesome and replace your image entirely by that. It's size scalable because of CSS and has a simpler syntax.
<button type="submit" class="imgbottom" onclick="ValidateSelection('selectedItems');">
<i class="fa fa-angle-double-right" aria-hidden="true"></i> Next
</button>
Then in your jQuery function:
function ValidateSelection(elementName){
var selectedItems = $("[name='" + elementName + "']:checked");
if (selectedItems === null || selectedItems.length === 0) {
var validationSummary = $('.validation-summary-errors ul');
if (validationSummary.length > 0 && $('.validation-summary-errors ul li').length == 0) {
validationSummary.append('<li>' + "Please select at least one item" + '</li>');
}
var errors = $("[name='ErrorMessage']");
if (errors.length > 0) {
errors.hide();
}
var buttonGenerateReport = $("#GenerateReport");
if (buttonGenerateReport.length > 0) {
buttonGenerateReport.hide();
}
event.preventDefault();
}
}

How to refresh the bootstrap multiselect checkbox and maintain original values of checkbox?

I am trying to refresh a bootstrap 3.0 multiselect control.
On refresh, I want to reset the checkboxes to its previous state when the partial view was first rendered
How can I achieve that?
I tried following approach but didn't get success.
Maintained hidden field for storing selected checkbox values once view
was rendered.
On Reset button click:
2.1 Uncheck all checkboxes.
2.2 Check only those checkboxes whose value I got from hidden field.
j('#btnReset11').click(function () {
j("#divErrorMessage ul li").not(':first').remove();
j("#divErrorMessage").hide();
j("#divSuccessMessage").hide();
j("#includeSelectAllOption").find("option").removeAttr("selected");
j("#chkRoles ul li").removeClass("active");
j("#chkRoles .btn-group").find("button").removeAttr('title');
j("#chkRoles .btn-group").find("button").text('Select');
var value = j("#selectedCheckboxes").val();
valueItems = value.split(", ");
for (var i = 0; i < valueItems.length; i++) {
j('#' + valueItems[i]).attr('selected', 'selected');
j("#chkRoles ul li input[value=" + valueItems[i] + "]").parent().parent().parent().addClass("active");
var title = j("#chkRoles .btn-group").find("button").title;
j("#chkRoles .btn-group").find("button").removeAttr(title);
}
if (valueItems.length > 0) {
j("#chkRoles .btn-group").find("button").text(valueItems.length + ' selected');
}
else {
j("#chkRoles .btn-group").find("button").text('Select');
}
});
j(document.body).on('click', '#btnReset-Button', function () {
j("#divErrorMessage").hide();
j(this).parents('.PopupModalClass').find('input[type="text"],input[type="email"],select').each(function () {
if (this.defaultValue != '' || this.value != this.defaultValue) {
this.value = this.defaultValue;
setTimeout(function () {
j('.PopupModalClass #multiSelectDropdown').multiselect('refresh');
});
} else { this.value = ''; }
});
});

Direct URL to overlay on the page

I have an overlay on my page and I would like to give user a link / URL which leads them directly to the page, with the overlay loaded.
Is it possible to be done? How do I do that?
This is my code:
$(function() {
$('#overlay_job').click(function() {
document.getElementById('iframe_job').src = "http://targeturl-for-my-overlay-content";
$('#overlay_bg2').fadeIn('fast',function(){
$('#overlay_box').fadeIn('fast');
});
});
$('#boxclose').click(function() {
$('#overlay_box').fadeOut('fast',function() {
$('#overlay_bg2').fadeOut('fast');
});
});
var overlay_bg2 = $("#overlay_box");
//var top = $(window).scrollTop() - (overlay_bg2.outerHeight() / 2);
var top=0;
var left = -(overlay_bg2.outerWidth() / 2);
overlay_bg2.css({ 'margin-top': top,'margin-left': left });
if(getUrlVars()["openJobOverLay"] == "Y") {
$('#overlay_job').trigger('click');
}
});
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
===========
and on the page, user can click on this link to get the overlay shown:
<a id="overlay_job" class="underline" href="javascript:void(0);%20opener.jobframe.location.reload();">
See job openings
</a>
<img src="link_arrow.gif" class="linkarrow">
</div>
Hide the overlay with CSS: display: none;. Give the overlay element an id, then add the id to the URL like so http://www.yourpage.com#id. Then use jQuery to do something like this:
$(document).ready(function(){
if(window.location.hash) $('#' + window.location.hash).show();
});
Edit:
In your specific case add this line as the last line inside your $(document.ready();.
$(function() {
// All of your code inside this function...
if(window.location.hash) $('#' + window.location.hash).click();
});
function getUrlVars() {
// Some more of your code...

jQuery autocomplete completely unresponsive

This is my first time really delving into jQuery with my ASP MVC3 intranet app. I need the autocomplete to be able to reference a list of items from a database. I followed the tutorial found here and thought "ok, that looks easy"... and now after implementing the code and researching other methods and bashing my head against the keyboard for at least four hours I'm not anywhere closer to making this work that before I wrote the code.
Here is the code from the view, w/the library declarations as well. FYI - I am taking over this project, so all the other javascript/Ajax you see was written by someone else with more experience than me. I put all the code in this section just in case something else is getting in the way.
<link href="../../Content/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#BankName").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
$(function () {
$("#drpProducerType").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#Role").val(value);
$('#DSSfields').removeClass('noSee');
$('#DSSfields').addClass('seeMe');
//alert("Role must be set to \"Sole Proprietor\" as well. Monet will do this for you!");
}
else {
//TO DO: add role stuff here as well
$('#DSSfields').removeClass('seeMe');
$('#DSSfields').addClass('noSee');
}
});
$("#Role").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#drpProducerType").val(value);
alert("Producer Type changed to \"Sole Proprietor\" as well");
}
});
});
function ChangeChannel() {
//this function called if Market Segment changes, to update the channel
var pendistcode = document.getElementById('Pendist');
if (pendistcode == null) alert('Error: Cannot find Market Segment control');
$.ajax({
type: 'POST',
url: '/AgentTransmission/GetChannel/',
data: { pendist: pendistcode.value },
success: function (data) {
// alert("success: " + data);
$('#channelName').html(data);
$('#Channel').val(data);
},
error: function (data) {
alert("failure to obtain Channel name");
}
});
CheckTerritory('channel');
} //end ChangeChannel
function CheckTerritory(category) {
//this function called when changes happen that could change the territory (inddist)
//if the channel changed, or the alignment indicator, update the Territory
if ((category == "channel") | (category == "align")) UpdateTerritory();
//only trigger if the state or zip changed on the aligned address
if ((category == "L") && ($('#AlignmentL').attr('checked'))) UpdateTerritory();
if ((category == "M") && ($('#AlignmentM').attr('checked'))) UpdateTerritory();
} //end CheckTerritory
function UpdateTerritory() {
var i = $('#INDDist').val();
var p = $('#Pendist').val();
// alert(":" + i + ":" + p + ":");
//if ((i == "") || (p == "")) return;
if (p == "") return;
if ($('#INDDist').val() == "864") {
$('#INDDist').val("701");
}
else {
if ($('#INDDist').val() == "") {
$('#INDDist').val("864");
}
}
} //end UpdateTerritory
function MoreCompanies(row) {
//if the user clicks on the plus sign, add more company rows
if (row == '3') {
$('#plus2').html(' ');
$('#row3').removeClass('noSee');
$('#row3').addClass('seeMe');
}
if (row == '4') {
$('#plus3').html(' ');
$('#row4').removeClass('noSee');
$('#row4').addClass('seeMe');
}
if (row == '5') {
$('#plus4').html(' ');
$('#row5').removeClass('noSee');
$('#row5').addClass('seeMe');
}
} //end MoreCompanies
function CompanyFields() {
} //end CompanyFields
function ShowHideTerritory() {
alert('sunshine');
} //end ShowHideTerritory
</script>
The text box the autocomplete is supposed to work on
<div class="M-editor-label">
Bank\Agency Name
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.BankName, new { id = "BankName" })
#Html.ValidationMessageFor(model => model.BankName)
</div>
and here is the GetBanks method from the controller. I've set a breakpoint at the first line of this method and I've never been able to get it to hit.
//GET
public JsonResult GetBanks(string search)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(search))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
EDIT
If I replace the current .autocomplete code with the code suggested by this method instead , I get the following error in Chrome's debugger:
Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method '/AgentTransmission/GetBanks'
Here's the new code, I put it in the exact same spot as what I was previously using:
$(document).ready( function() {
$('#BankName').autocomplete('#Url.Action("GetBanks", "AgentTransmission")', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].BankName };
}
return rows;
},
formatItem: function(row, i, n) {
return row.BankName + ' - ' + row.Description;
},
width: 300,
mustMatch: true,
});
});
I added an extra set of closing brackets to the autocomplete which cleared this up. The widget functions properly now.
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
});

SlickGrid styling after cell edit

I'm using SlickGrid (2.0) dataView with slick.editors. In the Grid, a user can edit any number of cells which then modifies the underlying grid data so that the edits are maintained when the grid scrolls. This works great. But I also want to provide visual feedback for all the edits since these are not saved to the database until user hit "Save Edits" button.
Problem is that the editor method resets the cell after it reads back the changed grid data. I need to maintain a background color change to indicate that it's been edited. Has anyone been able to do this?
Here is the relevent code (simple Integer editor):
function IntegerCellEditor(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function() {
$input = $("<input type=text class='edited' type=text style='font:normal 12px arial; width:95px; text-align:right; border:none;' />");
$input.bind("keydown.nav", function(e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
});
$('#saveChanges').removeAttr("disabled"); // remove disabled attribute from "Save Changes" btn
$input.appendTo(args.container);
$input.focus().select();
};
this.destroy = function() {
$input.remove();
};
this.focus = function() {
$input.focus();
};
this.loadValue = function(item) {
defaultValue = item[args.column.field];
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function() {
return parseInt($input.val(),10) || 0;
};
this.applyValue = function(item,state) {
item[args.column.field] = state;
};
this.isValueChanged = function() {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
};
this.validate = function() {
if (isNaN($input.val()))
return {
valid: false,
msg: "Please enter a valid integer"
};
return {
valid: true,
msg: null
};
};
this.init();
}
This line does nothing and I can't figure out how to do this:
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
Thanks
I am not an expert in SlickGrid but take a look a Example 14, I think it has similar information that would help you.
My idea would be something like:
subscribe to grid.onCellChange event
store changes in object
use grid.setCellCssStyles('highlight',changes) to update CSS or grid.addCellCssStyles
Hope that helps a little at least.

Resources