Dynamically adding elements with jquery error - javascript

Here is my fiddle : DEMO
According to data JSON, there are 2 "groups".
Each group has 2 "widgets" each.
Every widget has certain "controls"
Light/Brightness/Color controls can be there for Philips widget. They are associated with a switch/slider/color picker respectively.
for (var k = 0; k < data.groups[i].widgets[j].controls.length; k++) {
$("." + data.groups[i].name + " > .widgets-container > ." + data.groups[i].widgets[j].name + " > .widget-header > .widget-label > .row > .brandName").text(data.groups[i].widgets[j].brandName);
$("." + data.groups[i].name + " > .widgets-container > ." + data.groups[i].widgets[j].name + " > .widget-header > .widget-label > .row > .productName").text(data.groups[i].widgets[j].productName);
var controlDiv;
if (data.groups[i].widgets[j].controls[k].type === "SWITCH") {
controlDiv = lightControl();
} else if (data.groups[i].widgets[j].controls[k].type === "SLIDER") {
controlDiv = brightnessControl();
} else if (data.groups[i].widgets[j].controls[k].type === "PICKER") {
controlDiv = colorControl();
}
controlDiv = $(controlDiv).addClass(data.groups[i].widgets[j].controls[k].name);
$("." + data.groups[i].widgets[j].controls[k].name > ".control-name").text(data.groups[i].widgets[j].controls[k].name);
$("." + data.groups[i].name + " > .widgets-container").append(widgetDiv);
$(widgetDiv).append(controlDiv);
$(".container-box").append(groupDiv);
}
However, the elements are not getting appended as required from the JSON. Also, the labels for light/brightness/color control does not appear. Where am I going wrong?
Any help would be much appreciated.
Thank you.

here is the answer fiddle : AnswerFiddle
I fixed this issue by first creating DOM elements and then assigning/appending values to the DOM elements.
Earlier there was an issue because sometimes assigning of value would be attempted even before DOM element was created.
controlDiv = $(controlDiv).addClass("row " + (data.groups[i].widgets[j].controls[k].name).replace(/\s+/g, '-').toLowerCase()).prepend("<div class='col s7 controlName'>" + data.groups[i].widgets[j].controls[k].name + "</div>");
if (data.groups[i].widgets[j].controls[k].type === 'SWITCH') {
$(controlDiv).append('<div class="col s5 switch"><label>OFF<input type= "checkbox"><span class="lever"></span>ON</label></div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'SLIDER') {
$(controlDiv).append('<div class="col s5 center-align"><img src="images/brightness.png"></div><p class="col s7 range-field"><input type="range" min = "0" max = "100"/></p><div class="col s5 brightness-percentage center-align">60%</div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'PICKER') {
$(controlDiv).append('<input class="col s2" type="color" name="favcolor" value="#ff0000"><div class="col s3 colorHexValue center-align">#ff0000</div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'GRAPH') {
$(controlDiv).html("<img src='images/graph.png'>");
} else if (data.groups[i].widgets[j].controls[k].type === 'DETECTOR') {
$(controlDiv).html("<img src='images/motion.png'>")
}
widgetDiv.append(controlDiv);
groupDiv.append(widgetDiv);
$(".container-box").append(groupDiv);

Related

Run a javascript from a html table cell

I am using asp.net core 5 and I have the following cell in a table -
<td id="actionId" class="text-left">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
</td>
I am trying to call a javascript function and add html at designationplaceholder for each record in the table.
I have tried -
$('tr').each(function (i, item) {
var html = DesignationStatus($('#dedesignatedDateId').val(), $('#renewalDueId').val(), $('#nextRenewalDueAtId').val(), #(ViewBag.NumberOfDays));
$('#designationPlaceHolderHere').html(html);
});
Doesn't work properly.
I want to call the function, for each record, passing the appropriate values for each record.
Any ideas?
Thanks
[UPDATE]
This is the function I call -
function DesignationStatus(dedesignatedDate, renewalDue, nextRenewalDue, numberOfDays) {
var isRenewalDue = (renewalDue === 'true')
//Get today's date
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
//Create next renewal due date display value.
var reDate = new Date(nextRenewalDue);
var reDay = reDate.getDate();
var reMonth = reDate.getMonth() + 1;
var displayRenewalDate = (reDay < 10 ? '0' : '') + reDay + '/' + (reMonth < 10 ? '0' : '') + reMonth + '/' + reDate.getFullYear()
//Create de-designation date display value.
var deDate = new Date(dedesignatedDate);
var deDay = deDate.getDate();
var deMonth = deDate.getMonth() + 1;
var displayDedesignationDate = (deDay < 10 ? '0' : '') + deDay + '/' + (deMonth < 10 ? '0' : '') + deMonth + '/' + deDate.getFullYear()
//Calculate what one day is
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
//Parse the number off days passed in
var numOfDays = parseInt(numberOfDays);
//If no number has been passed in set to default of 90.
if (isNaN(numberOfDays)) {
numOfDays = 90;
}
//Start html string
var html = '<div>'
html += ' <label>Designation status:</label>'
html += ' </div>'
html += ' <div>'
//Get rest of html dependant on due date etc.
if (dedesignatedDate != null && dedesignatedDate != "") {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>De-designated on</label>' + ' ' + displayDedesignationDate
}
else {
if (nextRenewalDue != null && nextRenewalDue != "") {
var today = new Date();
var renewal = new Date();
today = Date.parse(todaysDate);
renewal = Date.parse(nextRenewalDue);
if (renewal > today) {
if (!isRenewalDue) {
html += ' <div class="alert alert-success" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Active</label>'
}
else {
html += ' <div class="alert alert-warning" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Due to renew - renew before </label>' + ' ' + displayRenewalDate
}
}
else if (renewal < today) {
//Work out the number of days between renewal and today's date
var diffDays = Math.round(Math.abs(((new Date(today).getTime()) - (new Date(renewal).getTime())) / (oneDay)));
if (diffDays < numOfDays) {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive - lapsed on </label>' + ' ' + displayRenewalDate;
}
else {
html += ' <div class="alert alert-danger" role="alert" style="text-align : center; height : 47.5px;">'
html += ' <label>Inactive</label>'
}
}
}
}
//Finish off the html string
html += ' </div>'
html += ' </div>'
html += '</div>'
//return html strin
return html
}
<td id="actionId" class="text-left" onclick="DesignationStatus('#clinic.VaccClinic.DedesignationDate','#clinic.RenewalDue','#clinic.VaccClinic.NextRenewalDueAt','#ViewBag.NumberOfDays')">
<input hidden id="renewalDueId" type="hidden" asp-for="#clinic.RenewalDue" class="form-control" />
<input hidden id="nextRenewalDueAtId" asp-for="#clinic.VaccClinic.NextRenewalDueAt" class="form-control" />
<input hidden id="dedesignatedDateId" asp-for="#clinic.VaccClinic.DedesignationDate" class="form-control" />
<div id="designationPlaceHolderHere"></div>
Training Status: <br /><br />
Annual Returns Figures:
#if (clinic.NumberOfVaccinations.HasValue)
{
<label>#clinic.NumberOfVaccinations.Value.ToString()</label>
if (clinic.NumberOfAdverseEvents.HasValue)
{
<label> - #clinic.NumberOfAdverseEvents.Value.ToString()</label>
}
else
{
<label> - 0</label>
}
}
else
{
<label style="background-color:red">
Not Submitted
</label>
}
This should call your javascript function. Also never use the same id="dedesignatedDateID".

using .on to listen for event not working

I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.

trying to filter out results with checkboxs

So I have these divs that are essentially results, I am trying to filter through said results using checkboxes and data-category tags.
Here is the code I am using below it works except for it should only show the divs if its data category tags match all checkboxes selected. But in this script if you select boditrak, trackman, and indoor it will show each result that has any of those not just the ones that contain each tag
JSFiddle
<html>
<head>
<title>Test</title>
</head>
<body>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
</script>
</html>
The problem is with comma , which you are adding between each [data-category~=] in selector variable. So jQuery is looking for element which has any one of these data-category. So just remove comma, then only jQuery will start looking for those element which have all those data-category
Your selector value should be [data-category~='trackman'][data-category~='boditrak'] instead of [data-category~='trackman'],[data-category~='boditrak']
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>

Disable unchecked check boxes in selected div element using jquery

I am creating check boxes dynamically using jquery. I want to disable unchecked check boxes as shown in the snippet,but i want to disable the check boxes only in their respective div elements and not in the other div elements which is what causing issue now.
I have written the code to disable/enable checkboxes based on their respective div tags and i have commented it as it is throwing error if enabled.
$($(".checkbox").eq(id).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Problem explanation : Here i am creating two div tags dynamically inside which check boxes are also created with same name. So if i check on checkbox in first div other checkbox gets disabled and other div tag gets created which works as expected. but if i check any option in second div tag other option in second div tag doesn't get disabled and also if i uncheck the checked option in first div tag both options get disabled in first div tag. I guess this is because all checkboxes have same names.
How can we disable checkboxes only in their respective div tags. I tried below code but didn't work
$($(".checkbox").eq(1).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Below snippet explains the problem more appropriately
Please help me.
function checkdiv(id, val) {
if ($(":checkbox[name='radio']:checked").length == 1)
$(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>
Have you tried ".find" in the jQuery API - this will only find elements within the specified selector - see the modifications to the "checkdiv" function ($('#' + id))
function checkdiv(id, val) {
if ($('#' + id).find(":checkbox[name='radio']:checked").length == 1)
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>

Recursive previous and next in arrow key press in custom autocomplete with jquery

I have developed customise autocomplete which works fine in terms of data pulling and displaying in the page. I want to enhance it. I want to implement something like this (multiple dataset of typeahead pluggin) where I want to select or set focus on the next and previous li of my autocomplete when down / up arrow key is pressed. Here is my jquery code which populate the autocomplete.
$("input[data-tg-autocomplete]").keyup(function (e) {
if (e.keyCode == 40 || e.keyCode == 38) {
//alert(e.keyCode);
DownUpKeyPress(e.keyCode);
}
else {
var $input = $(this);
//-----------------------------Allowing user to enter atleast one character for auto search
if ($input.val().length > 0) {
var request = $.ajax({
url: $input.attr("data-tg-autocomplete"),
method: "GET",
data: { term: $input.val() },
dataType: "json"
});
request.done(function (JsonData) {
LoadAutoSuggest(JsonData);
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
});
}
}
});
//========================populate autocomplete
function LoadAutoSuggest(result) {
var tag = "";
$('.custom-autocomplete').html("");
if (result.Destination != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Destination";
tag = tag + "</a>";
tag = tag + "</li>";
for (i = 0; i < result.Destination.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Destination' data-id='" + result.Destination[i].DestinationID + "'>";
tag = tag + "<div>";
tag = tag + result.Destination[i].DestinationName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
}
}
if (result.Business != undefined) {
tag = tag + "<li class=''>";
tag = tag + "<a href='#' class='list-group-item active disabled AutoCompleteHeader'>";
tag = tag + "Business";
tag = tag + "</a>";
tag = tag + " </li>";
for (i = 0; i < result.Business.length - 1; i++) {
tag = tag + "<li class='list-group-item'>";
tag = tag + "<a class='autocompleteListItem' data-type='Business' data-id='" + result.Business[i].BusinessID + "'>";
tag = tag + "<div>";
tag = tag + result.Business[i].BusinessName;
// tag = tag + "<span class='pull-right badge'>14</span>";
tag = tag + "</div>";
tag = tag + "</a>";
tag = tag + "</li>";
//alert(result.Business[i].BusinessName + " ID = " + result.Business[i].BusinessID)
}
}
$('.custom-autocomplete').html(tag);
$('.autocompleteListItem').click(function () {
var id = $(this).attr("data-id");
var type = $(this).attr("data-type");
var text = $(this).text();
$("#searchtext").val(text);
$('.HiddenSearchInput #id').val(id);
$('.HiddenSearchInput #type').val(type);
$('.custom-autocomplete').html("");
$('.Search-submit').trigger("click");
});
$(':not(".search-wrapper")').click(function () {
if ($('.custom-autocomplete li').length > 0) {
$('.custom-autocomplete').html("");
}
});
$('.custom-autocomplete li.list-group-item').first().addClass("focused");
}
function DownUpKeyPress(keyCode) {
//$this = $(this);
if (keyCode == 40) {
// alert('40');
// $this.next().focus();
if ($('.custom-autocomplete li').length > 0) {
var $focused = $('.custom-autocomplete li.focused');
$('.custom-autocomplete li.focused ~ .list-group-item').first().addClass('focused')
$focused.removeClass('focused')
}
return false;
} else if (keyCode == 38) {
//alert('38');
// $this.prev().focus();
if ($('.custom-autocomplete li').length > 0) {
}
return false;
}
}
and here is my html where I am populating the autocomplete
<div class="Search-container">
<span class="error search-validation"></span>
<div class="input-group input-group-lg">
<input id="searchtext" name="searchtext" type="text" class="form-control " placeholder="Find travel agents, search travel agents in your destination" data-tg-autocomplete="#Url.Action("AutocompleteBusiness")" />
<span class="input-group-btn">
<button class="btn btn-primary Search-submit" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div><!-- /input-group -->
<div class="displaynone HiddenSearchInput">
<input type="hidden" id="id" name="id" value="" />
<input type="hidden" id="type" name="type" value="" />
</div>
</div>
<ul class="list-group custom-autocomplete">
#*List will be populated from ajax call in function LoadAutoSuggest*#
</ul>
My function DownUpKeyPress is for setting focus for next and previous li. Focused li item will be used for site search but I am not been able to set focus on the next and previous li when up/down arrow is pressed. I am using MVC5 for developing my project. Probably I am wrong with jquery. May someone help me out to fix the issue. I dont want to use any pluggin for this.
Add this code in DownUpKeyPress
// for up arrow => Previous Li Focus
if (keyCode == 40) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').next('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').first().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').next('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').next('li').addClass('focused');
}
}
return false;
}
// for down arrow => Next Li Focus
else if (keyCode == 38) {
if ($('.custom-autocomplete li').length > 0) {
var oBox = $('.custom-autocomplete > .list-group-item.focused').prev('li');
var curClass = oBox.attr("class");
if (oBox.length == 0) {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused');
$('.custom-autocomplete > .list-group-item').last().addClass('focused');
}
else if (curClass == "") {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').prev('li').addClass('focused');
}
else {
$('.custom-autocomplete > .list-group-item.focused').removeClass('focused').prev('li').addClass('focused');
}
}
return false;
}

Categories

Resources