KendoDropdown with disabled default option - javascript

I`m filling a kendo dropdown with a function but I would like for the default value to be "Select Option" which you wont be able to select it back once you select another one.
function FillInDropDown(dataSet,ddID) {
var dropDown = $(ddID);
if (!dataSet.error) {
var i;
var values = [];
// Apppend the other options on dataSet
for (i = 0; i < dataSet.dropdownData.length; i++) {
values.push(dataSet.dropdownData[i]);
}
// Clearing Values
$(ddID).empty();
$(ddID).kendoDropDownList({
dataSource: [],
animation: false
});
$(ddID).data("kendoDropDownList").dataSource.data(values);
$(ddID).data("kendoDropDownList").value(values[0]);
}
else {
simpleDialog.info(dataSet.ErrorMessage);
}
};

Here are two alternatives that you can pursue:
After the user picks a value, remove the optionLabel item from the list and refresh it.
After the user picks a value, prevent the selection of the optionLabel item via the select event.
You will need a one-time handler for the change event of the DropDownList.
Here is an example for both options:
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/dropdownlist/remotedatasource">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.914/styles/kendo.default.min.css" />
<script src="//kendo.cdn.telerik.com/2016.3.914/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
</head>
<body>
<p>The optionLabel will be removed:</p>
<input id="products1" />
<p>The optionLabel selection will be prevented:</p>
<input id="products2" />
<script>
$(function() {
var settings = {
optionLabel: "Select a product",
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
transport: {
read: {
dataType: "jsonp",
url: "//demos.telerik.com/kendo-ui/service/Products",
}
}
}
};
$("#products1").kendoDropDownList(settings);
$("#products2").kendoDropDownList(settings);
$("#products1").data("kendoDropDownList").one("change", function(e) {
e.sender.list.find(".k-list-optionlabel").remove();
e.sender.refresh();
});
$("#products2").data("kendoDropDownList").one("change", function(e) {
e.sender.bind("select", function(j){
if (j.dataItem.ProductID == "") {
j.preventDefault();
}
});
});
});
</script>
</body>
</html>

Related

how to use variable inside my function in javasript?

<script type='text/javascript'>
$(document).ready(function () {
$("#q").keyup(function () {
var value = $('#q').val()
$.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function (data) {
var text = []
for (var i = 0; i < 5; ++i) { text.push(data.results[i].ifsc) }
// var text = `IFSC: ${data.results.ifsc}`
if (document.getElementById("q").value.length == 0) { text = [] }
// console.log(text)
$('#q').hover(
function () {
console.log(text)
$("q").autocomplete({
source: text,
delay: 500
});
}, function () {
$("#q").autocomplete("disabled");
})
})
})
})
</script>
I have created variable text to store results from get request. My autocomplete function is inside the getJSON function. i have checked consolelog if its printing anything. Inside of hover function it doesnt print anything, but outside statement when commented out prints results. I dont understand why this is happening. I need this so that my autocomplete wont show results when user deletes all input or is not hovering over it.
Update
I changed $(this).hover to $("#q").hover, as it would trigger hover event for wherever mouse is. still nothing changed
I think you can simplify this a bit and use the actual enable/disable.
I used the long form of the hover (mouseenter, mouseleave) for clarity
$(function() {
$("#q").on('keyup', function() {
var value = $('#q').val();
/* $.getJSON("{% url 'api:api-root' %}" + "bankdetailapi/?q=" + value, function(data) {
var text = [];
for (var i = 0; i < 5; ++i) {
text.push(data.results[i].ifsc);
}
// var text = `IFSC: ${data.results.ifsc}`
if (document.getElementById("q").value.length == 0) {
text = [];
}
});
*/
}).on('mouseenter', function() {
console.log("Initial:", $(this).val());
$(this).autocomplete("enable");
}).on("mouseleave", function() {
// this will break the autocomplete (not choose a value) so you would have to do that manually
// $(this).autocomplete("disable");
}).autocomplete({
source: [{
label: "Choice1",
value: "value1"
}, {
label: "Choice2",
value: "value2"
}, {
label: "Party",
value: "beer"
}],
delay: 500,
select: function(event, selectedObject) {
jQuery(this).val(selectedObject.item.value);
}
});
});
.ui-autocomplete {
position: absolute;
cursor: default;
z-index: 1001 !important
}
.ui-front {
z-index: 1500 !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/jquery-ui.min.css" integrity="sha512-ug/p2fTnYRx/TfVgL8ejTWolaq93X+48/FLS9fKf7AiazbxHkSEENdzWkOxbjJO/X1grUPt9ERfBt21iLh2dxg==" crossorigin="anonymous"
referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/cupertino/theme.min.css" integrity="sha512-adRIgePtMQgAVB+Mfkhl+Nyva/WllWlFzJyyhYCjznU3Di+Z4SsYi1Rqsep11PYLpUsW/SjE4NXUkIjabQJCOQ==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="ui-widget">
<label for="q">Tags: </label>
<input id="q" type="text">
</div>
Consider an alternative example.
$(function() {
$("#q").autocomplete({
source: function(request, response) {
var myUrl = "{% url 'api:api-root' %}" + "bankdetailapi/";
$.ajax({
url: myUrl,
data: {
q: request.term
},
success: function(data) {
var text = [];
$.each(data.results, function(i, res) {
if (i < 5) {
text.push(res.ifsc);
}
});
response(text);
}
})
},
delay: 500,
minLength: 0
}).hover(function() {
if ($(this).val() != "") {
$(this).autocomplete("search", $(this).val());
}
}, function() {
$(this).autocomplete("close");
});
});
.ui-autocomplete {
position: absolute;
cursor: default;
z-index: 1001 !important
}
.ui-front {
z-index: 1500 !important;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="q">Tags: </label>
<input id="q" type="text">
</div>
See More: https://api.jqueryui.com/autocomplete/

Datatables: column search with stripped HTML

Referencing to the Datatables API.
I implemented individual column searching and need to extend it:
There is a column which is displaying a button with HTML-Attributes/Classes applied. The Problem: I need to strip HTML in order to search the button's caption only. Any ideas how can I do that?
Here's my code:
table().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function (e) {
if (e.which == 27) {
$(this).val('');
}
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
I believe, you may need to employ external (custom) search function $.fn.DataTable.ext.search in order to look for button texts only (if that's what you're trying to achieve).
You may find the demo below:
//Sample source data
const srcData=[
{title:'apple',cat:'fruit',score:'good'},
{title:'strawberry',cat:'berry',score:'good'},
{title:'broccoli',cat:'vegie',score:'bad'},
{title:'durian',cat:'fruit',score:'bad'}
];
//Global variable for button text custom search
var buttonText = '';
//DataTables initialization
const dataTable = $('#mytable').DataTable({
dom: 't',
data: srcData,
columns: [
{title: 'title', data: 'title'},
{title: 'category', data: 'cat'},
//render score property as a button
{title: 'score', data: 'score', render: (data, type, row, meta) => `<button>${data == 'good' ? 'Love it!' : 'Hate it!'}</button>`}
],
});
//Append <tfoot> and searchbars
$('#mytable').append('<tfoot><tr></tr></tfoot>');
dataTable.columns().every(function () {
$('#mytable tfoot tr').append(`<td><input colindex="${this.index()}"></input></td>`);
});
//Custom search function across button text only
$.fn.DataTable.ext.search.push((settings, row, rowIndex, rowData, counter) => $(dataTable.row(rowIndex).node()).find('td:eq(2) button').text().toLowerCase().includes(buttonText) || buttonText == '');
//Listen for 'keyup' in <tfoot> searchbars
$('#mytable').on('keyup', 'tfoot td input', function () {
const colindex = $(this).attr('colindex');
//If it's input in 3-rd column (colindex==2)
//simply assign global variabl and re-draw
//table to apply custom search
if (colindex == 2) buttonText = $(this).val().toLowerCase();
//Otherwise search by corresponding column
else dataTable.column(colindex).search($(this).val());
dataTable.draw();
});
tfoot td {
padding-left: 10px !important
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>

Trying to use Find (Hightlight) in AlanJuden.MvcReportViewer - asp.net.core

Report Paging works, Refresh works, Export (with some probs) and Print works but Find does not highlight anything.
Find code is:
function findText() {
$('.ReportViewerContent').removeHighlight();
var searchText = $("#ReportViewerSearchText").val();
if (searchText != undefined && searchText != null && searchText != "") {
showLoadingProgress('Searching Report...');
var params = $('.ParametersContainer :input').serializeArray();
var urlParams = $.param(params);
var page = parseInt($('#ReportViewerCurrentPage').val());
$.get("/Report/FindStringInReport/?reportPath=#Model.ReportPath.UrlEncode()&page=" + page + "&searchText=" + searchText + "&" + urlParams).done(function (data) {
if (data > 0) {
viewReportPage(data, function () {
$('.ReportViewerContent').highlight(searchText);
hideLoadingProgress();
});
} else {
$('.ReportViewerContent').highlight(searchText);
hideLoadingProgress();
}
});
}
}
Scripts in _Layout are:
<script src="~/lib/jquery/dist/jquery-3.3.1.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
Scripts in Report Viewer are:
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/select2.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/select2-bootstrap.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/mvcreportviewer-bootstrap.css" />
<script src="~/lib/bootstrap/dist/js/select2.min.4.0.3.js"></script>
<script src="~/lib/jquery/dist/jquery.highlight-5.js"></script>
Have tried options like:
$('.ReportViewerContent').highlight(searchText, { wholeWord: false, ignoreCase: true, color: "#ffff00", bold: true });
Any thoughts please.
I have just tested on my working environment and it is highlighting. It does require a css class for it to highlight appropriately. So be sure that you have a ".highlight" style similar to this:
.highlight { background-color: yellow; }

Using Jquery chosen in jquery ajax

I am using jquery chosen and calling ajax on change drop down but records are not displaying. This code which I am using after changing drop down.
$.ajax({
type: "POST",
url: "MY URL",
data: {
sno: $(this).val()
},
success: function (resp) {
var resp = jQuery.parseJSON(resp);
if (resp.length == 0) {
$("#site").html('<option value="0" selected>Select Site</option>');
} else {
$.each(resp, function (i, item) {
$('#site').append($('<option>', {
value: item.siteNameID + '-' + item.siteName,
text: item.siteName
}));
});
}
},
error: function (resp) {
console.log('error');
}
});
One thing I have noticed jquery chosen applying on my select box but data which I am fetching from server side is not adding in that select box
You will need to call the chosen update trigger after you add items to your select list dynamically in order for them to show up. Use the following line after you have appended items and they should be displayed in your list.
$('#site').trigger("chosen:updated");
I think my code is not the answer for your question, but this mimics adding options to select... just click the add button...
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="add()">Add</button>
<select id="select"></select>
<script>
var json = [{title:"lorem",value:1},
{title:"john doe",value:2},
{title:"foo",value:3},
];
function add(){
$("#select").empty();
for(var x = 0; x<json.length; x++){
var option = '<option value="'+json[x].value+'"> '+json[x].value+'-'+json[x].title+'</option>';
$("#select").append($(option));
}
}
</script>
</body>
</html>

Using HTML5 local storage to store list items <ul>

I am creating a basic to-do list and was wondering on how to store my list so that when a user comes back to the page or accidentally refreshes the browser window, the list will still be available?
html
<!DOCTYPE html>
<html>
<head>
<title>My To-Do List</title>
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/font-awesome-animation.min.css">
<link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
</head>
<body>
<div id="page">
<header>
<img src="images/checklist.png" alt="some_text">
</header>
<h2>MY TO-DO LIST</h2>
<ul id="sortable"></ul>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add Description" maxlength="40" />
<input type="submit" id="add" value="add" />
<div id="double">Drag and drop to rearrange items
<br />Click on an item to remove it</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="js/sort.js"></script>
<script src="jquery-ui/jquery-ui.js"></script>
</body>
</html>
JavaScript/jQuery
$(function () {
var $list;
var $newItemForm;
var $newItemButton;
var item = '';
$list = $('ul');
$newItemForm = $('#newItemForm');
$newItemButton = $('#newItemButton');
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function (e) {
e.preventDefault();
var text = $('input:text').val();
$list.append('<li>' + text + '</li>');
$('input:text').val('');
});
$list.on('click', 'li', function () {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
$this.animate({}, 500, 'swing', function () {
$this.remove();
});
} else {
item = $this.text();
$this.remove();
}
});
});
localStorage.setItem($list);
//add animations when you learn how to...
You need to keep the data in an object also. Currently its only in DOM. Everything you add a new todo or edit an existing todo, you need to save that to the localstorage. Storing DOM nodes to localStorage wont work. localStorage also only accept string values.
So this is how I would change your code:
// localStorage key
var lsKey = 'TODO_LIST';
// keeping data
var todoList = {};
function getSavedData () {
var fromLs = localstorage.getItem( lsKey );
if ( !! fromLs ) {
todoList = JSON.parse( fromLs );
} else {
todoList = {};
localstorage.setItem( lsKey, todoList );
};
};
function saveData () {
var stringify = JSON.stringify( todoList );
localstorage.setItem( lsKey, todoList );
};
$newItemForm.on('submit', function(e) {
e.preventDefault();
var text = $('input:text').val().trim(),
uuid = new Date.now();
// lets use input[type:checkbox] to determine if complete or not
if ( !! text ) {
todoList[uuid] = text;
$list.append('<li><input type="checkbox" id=' + uuid + ' /> ' + text + '</li>');
$( 'input:text' ).val( '' );
};
};
$list.on('change', 'li input', function() {
var uuid = $(this).attr( 'id' ),
$li = $(this).parent();
if ( $(this).prop('checked') ) {
todoList[uuid] = undefined;
delete todoList[uuid];
saveData();
$li.fadeOut("slow", function() {
$this.remove();
};
};
});
Good luck, have fun!
You have to do 2 things: first is to store ony your data, not html. Second thing is that you have to provide a name for your item in localStorage because this is a key/value storage, so it needs a name for a key. Also because localStorage stores all data as a string value, call JSON.stringify() on your data before you sore it. So your code will be something like this: localStorage.setItem("yourKeyName", JSON.stringify(yourDataObj)). And when you want to read your data from it do JSON.parse(localStorage.getItem("yourKeyName")) to get your data as json object

Categories

Resources