JQuery's Change() event don't catch values selected by autocomplete - javascript

I have an Onchange Event Defined on a Textbox as below
$('input[ComponentAttribute]').on("change",function () {
dataTxt = "";
var thisID = $(this).attr('id');
var temp = $('#' + thisID).val();
if (!(temp.trim()=='')) {
// alert($(this).attr('ComponentAttributeID') + " - " + temp);
placeholder[$(this).attr('ComponentAttributeID')] = temp;
for (var key in placeholder) {
if (key === 'length' || !placeholder.hasOwnProperty(key)) continue;
var value = placeholder[key];
dataTxt += key + ":" + value + ";";
}
$('[DataAttributeValue]').text(dataTxt);
}
});
Now, the event fires when user enters value by keyboard. But when user selects a value from Autocomplete as shown, the Event don't fire. What am I missing here?

Related

How to get on row click value from different cells?

Actually i'm trying to set value of a td inside a table in a variable but i'm getting the
row.getElementByTagName is not a function
at selectRow (user.aspx?ID=2:47)
The function is called on tr onclick and has as attribute this
While now i just would show the value of 2nd and 3rd td in an alert.
Here is the script
function selectRow(row) {
var firstInput = row.getElementsByTagName('input')[0];
var user = row.getElementByTagName('td')[1];
var soft = row.getElementByTagName('td')[2];
firstInput.checked = !firstInput.checked;
if (firstInput.checked) {
alert("AGGIUNGI " + user + " " + soft);
//document.getElementById('frame').src = "user.aspx?ADDUSER=" + user + "&SOFT=" + soft;
} else {
//document.getElementById('frame').src = "user.aspx?DELUSER=" + user + "&SOFT=" + soft;
alert("ELIMINA " + user + " " + soft);
}
}
You can do this in jQuery
var tds = $(row).find("td");
var user = tds.get(1);
var soft = tds.get(2);

Chart.js 2.7.2- Multiline get point value onClick

I would like to get value foreach point value.
Don't work because when I click on point I obtain only of the first line value.
GetElementsAtEvent give me an array of 3 element (element active) but how I can get the clicked value?
This the Complete code.
$(document).on("click", "#canvas", function(event){
var activePoints = ctx.getElementsAtEvent(event);
if(activePoints.length > 0){
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementindex = activePoints[0]._index;
var label = ctx.data.labels[clickedElementindex];
var value = ctx.data.datasets[clickedDatasetIndex].data[clickedElementindex]["y"];
alert("Clicked: " + label + " - " + value);
}
});
Thanks
To get the exact element, use ctx.getElementAtEvent.
$(document).on("click", "#canvas", function(event){
var activePoint = ctx.getElementAtEvent(event);
if (activePoint.length > 0) {
var clickedDatasetIndex = activePoints[0]._datasetIndex;
var clickedElementIndex = activePoints[0]._index;
var clickedDatasetPoint = ctx.data.datasets[clickedDatasetIndex];
var label = clickedDatasetPoint.label;
var value = clickedDatasetPoint.data[clickedElementIndex]["y"];
alert("Clicked: " + label + " - " + value);
}
});

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

How to trigger the button when user click enter key using Jquery?

I have a
TextBox (id=txtFilterValue),
Add button (id=btnAdd) and
Table (id=queryTable)
once user enter the value in text box, they may press the enter key. So when they press the enter key, it should call the Add Button which is already defined in jquery.
This is What I tried
Jquery Code
//Preventing ENTER Key
$('#form1').on('keyup keypress', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
//$('input[name = btnAdd]').click();
$("#btnAdd").trigger('click');
e.preventDefault();
return false;
}
});
The above code to prevent the enter key and it will call the Add Button.
As I thought it's working. But it's calling two times and the values are adding 2 times. It shouldn't add two times.
when I click the Add button directly, it's entering the record only one to my table.
This is my button Add code
//Filter Query Add to TABLE and TEXTBOX
$("#btnAdd").click(function () {
var selectedField = $("#FilterField option:selected").text();
var operator = $("#ddlOperator :selected").val();
var filterValue = $("#txtFilterValue").val();
var query;
var textFilterRecord = $("#txtFilterRecord").val();
//values seperated by COMMA
var arrayTxtConditionValue = filterValue.split(',');
if (operator == 'equalTo') {
if ($("#txtFilterRecord").val().length == 0) {
//put the single quotation( ' ) in between values
var filterCommaValue = '';
for (var i = 0; i < arrayTxtConditionValue.length; i++) {
if (i == 0) {
filterCommaValue = filterCommaValue + "'" + arrayTxtConditionValue[i] + "'";
}
else {
filterCommaValue = filterCommaValue + ",'" + arrayTxtConditionValue[i] + "'";
}
}
query = selectedField + ' IN(' + filterCommaValue + ') ';
$("#txtFilterRecord").val($("#txtFilterRecord").val() + query);
$("#queryTable > tbody:last-child").append('<tr><td class="FieldNameID">' + selectedField + '</td><td class="OperatorID"> IN(' + filterCommaValue + ')</td></tr>');
}
else {
var filterCommaValue = '';
for (var i = 0; i < arrayTxtConditionValue.length; i++) {
if (i == 0) {
filterCommaValue = filterCommaValue + "'" + arrayTxtConditionValue[i] + "'";
}
else {
filterCommaValue = filterCommaValue + ",'" + arrayTxtConditionValue[i] + "'";
}
}
var radioButton = $('input[name=group]:checked').val();
query = radioButton + ' ' + selectedField + ' IN(' + filterCommaValue + ') ';
$("#txtFilterRecord").val($("#txtFilterRecord").val() + query);
$('#queryTable > tbody:last-child').append('<tr><td class="FieldNameID">' + radioButton + ' ' + selectedField + '</td><td class="OperatorID"> IN(' + filterCommaValue + ')</td></tr>');
}
}
});
$('#form1').on('keyup keypress', function (e) {
// ...
Here you are listening for two events with the same callback. That means whenever one of them occur the callback will be called. Since they're both related to the key events (both are pretty much the same), the callback will be called twice.
So just remove one of them like this:
$('#form1').on('keypress', function (e) {
// ...

Global variable does not increment

Most of the action is in the function next. The other functions are provided for context. The global variable tally increments as it should when the right answer is selected. However the variable nr is not incremented and I can't figure out way it is not.
You can see that I commented out that the next function returned an object with tally and nr and assigned those values in the event listener. When I did it that way, it worked. But it should work the other way as well, right.
var nr = 0;
var tally = 0;
function onLoadEvent(nr) {
//alert('onload');
var quiz = document.getElementById('quiz');
var question = allQuestions[nr];
var next = quiz.lastElementChild;
var qHeader = "<h2>" + question.question + "</h2>";
var q = "";
for(var i=0;i<question.choices.length;i++){
q = q + '<p><label for="a' + i + '">' +
'<input type="radio" id="a' + i + '" name="q" value="' +
i + '">' + question.choices[i] + '</label></p>';
}
quiz.innerHTML = qHeader + q + next.outerHTML;
//next = document.getElementById('next');
}
function getChecked(){
var radios = document.getElementsByName('q');
var radio;
for(var i=0;i<radios.length;i++){
if(radios[i].checked){
radio = radios[i];
break;
}
}
return radio;
}
function next(nr){
if (getChecked() !== undefined) {
var answer = getChecked();
if(answer.value == allQuestions[nr].correctAnswer){
tally = tally + 1;
}
nr = nr + 1;
if (nr>=allQuestions.length){
alert("You got " + tally + " points!");
} else {
onLoadEvent(nr);
}
} else {
alert('You need to check a radio button');
}
//return {nr: nr, tally: tally};
}
var form = document.getElementById('quiz');
form.addEventListener('click', function(event){
if(event.target.id === 'next'){
next(nr);
//nr = obj.nr;
//tally = obj.tally;
} else if(event.target.id === 'prev'){}
}, false);
window.addEventListener('load', function(event){onLoadEvent(nr);}, false);
You are accepting parameters with same name nr which is hiding global scope nr.
Solution to your problem is remove nr as parameter. So use function onLoadEvent() instead of function onLoadEvent(nr)

Categories