Javascript assignment between two select lists not working - javascript

I have an MVC project in where I have two selectlists: one that is displayed to the user, and one that is hidden that contains my viewdata that the displayed one pulls from.
My Javascript function that triggers onchange for another selectlist is as follows:
function select()
{
document.getElementById("SelectedServer").innerHTML = document.getElementById("ServerSelect").value;
var services = document.getElementById("ServiceSelect");
services.options = serviceoptions.options;
console.log(services.options === serviceoptions.options)
var servers = document.getElementById("ServerSelect").selectedOptions;
for (i = 0; i < services.length; i++)
{
for (j = 0; j < servers.length; j++)
{
if (services.options[i].value == servers.item(j).value) { }
else (services.options[i] = null)
}
}
}
This function updates a text field with the selected servers, assigns my services selectlist with the options from the hidden data selectlist called "serviceoptions", and then sorts it so that the services are displayed only if they match the selected server (using value).
For some reason, when I do my options assignment (services.options = serviceoptions.options;), it runs without errors but clearly does not assign the options correctly.
The console output I put to test returns false, and chrome debugger shows that the length has not been updated.
I want to assign the options variable of serviceoptions to the options variable of services. Why can I not do this?
The issue I'm trying to solve with the hidden field is that before, my services would correctly disappear if they did not match, but I had no way to bring them back if the user selected another server.
I cannot use ajax to make another API call to retrieve the servers/services again.

Related

Invalid postback or callback argument. Event validation is enabled using pages enableEventValidation=true

I have the function below which i use to add items to a listbox and it can add the items and i save my changes on button click.
function add_Items() {
var gdOption = document.createElement("OPTION");
for (var i = 0; i < document.getElementById("ListBox_AllItems").length; i++) {
if (document.getElementById("ListBox_AllItems").options[i].selected == true) {
gdOption.text = document.getElementById("ListBox_AllItems").options[i].text;
gdOption.value = document.getElementById("ListBox_AllItems").options[i].value;
document.getElementById("ListBox_ItemsRecovered").add(gdOption);
document.getElementById("ListBox_AllItems").removeChild(document.getElementById("ListBox_AllItems").childNodes[i]);
}
}
get_all_Items();
}
The above code has a bug. The bug is if an item has already been added, it can still be selected and added a multiple times which creates duplicates. To try and fix that bug i modified the function as below.
function add_Items() {
var sourceSelection;
var targetSelection;
var i;
sourceSelection = document.getElementById('ListBox_AllItems');
targetSelection = document.getElementById('ListBox_ItemsRecovered');
i = sourceSelection.options.length;
while (i--) {
if (sourceSelection.options[i].selected) {
targetSelection.appendChild(sourceSelection.options[i]);
}
}
get_all_Items();
}
The above modification has created a bigger problem now. After adding items, now when i click the save button to save my changes, the page posts back as it was doing before but throws the below error, does any one know how i can fix this problem. Now the error it is throwing is below.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I have read posts mentioning that using if(!page.ispostback) {code} in page load before databinding my listboxes would solve the issue but that has not worked. I'm targeting .NET 4.7.2
Alternatively, how would i modify my original function that was not throwing this exception such that it does not add duplicates to my listbox?

multiple kendo grids using one script

I'm loading multiple partial views into the same cshtml page. All goes well until they need to use the scripts. As i'm using code like
var grid = $("#grid").data("kendoGrid");
var selected = grid.selected();
This code works fine with one grid, but starts showing issues when multiple grids are in place. The problem is that "#grid" is a reference to the name of the kendo grid. Is there a way to make this dynamic so it can be used by multiple grids?
I think the same problem would occur when there are multiple grids in the same page as it can't distinct what grid to refer to. Giving the grids different id's would work, but then the code in the script will return an undefined error on grid.selected().
Update:
So the solution of using
var grid = $(".k-grid").data("kendoGrid");
works to a certain point. It loads the data into the grid, but fails to do anything else. For example a part of my code for enabling an update and delete button doesn't work on the 2nd and 3rd partial view.
var grid = $(".k-grid").data("kendoGrid");
var selected = grid.select();
if (selected.length > 0) {
$("#btnCopy,#btnEdit,#btnDelete").removeClass("k-state-disabled");
} else {
$("#btnCopy,#btnEdit,#btnDelete").addClass("k-state-disabled");
}
Somehow the code only starts working for grid 2 and 3 after i have selected a row on grid 1, which is not as intended.
Instead of id(#Grid) you can use class(.k-grid):
var grid = $(".k-grid").data("kendoGrid");
The solution I found with help of a senior programmer is to save the grid data into a global variable like this.
var PartialGridData = PartialGridData || {};
After that I'm setting and changing the variable whenever changing the partial view.
PartialGridData.selectedGrid = $("#PartialGrid1").data("kendoGrid");
Where the name #PartialGrid1 is the name of the current grid.
This means I need to write this code as many times as I have grids, but it also fixes a lot of problems. After that I use it to select the correct data.
var grid = PartialGridData.selectedGrid;
var selected = grid.select();
if (selected.length > 0) {
$("#btnCopy,#btnEdit,#btnDelete").removeClass("k-state-disabled");
} else {
$("#btnCopy,#btnEdit,#btnDelete").addClass("k-state-disabled");
}
Another option would be to use e.sender.
function onRowSelect(e) {
var grid = e.sender;
var selected = grid.select();
if (selected.length > 0) {
$("#btnCopy,#btnEdit,#btnDelete").removeClass("k-state-disabled");
} else {
$("#btnCopy,#btnEdit,#btnDelete").addClass("k-state-disabled");
}
}
Both solutions have their drawbacks though. Not all methods get the variable e used for e.sender and changing partial views in a way that is not caught will cause the global variable not to be updated, so this has to be kept in check.

Creating list item dynamically in chrome extension

I am new to jquery. I am making a chrome extension which gets some DOM element from - say for example, any price of product from flipkart.
So, i want to make a list of each product's price user is viewing at the moment. I am able to get the price. But what i want to do, is make a closable list in my popup.html file, when i get the product price.
It's like, price should be dynamically displayed or added as a closable list when i get the price's data. I don't know how it can be achieved. I am confused here. Can you guide me please?
myfile.js
var ulcontainer = $('<ul></ul>');
$('body').append(ulcontainer);
$ ('ul').css('list-style','none');
for (var i = 0; i < 3; i++) {
dothis();
}
function dothis()
{
$('ul').append("<li></li>")
var imgdiv = $('<div></div>').text("this is imgdiv"); /// prod
var detaildiv = $('<div></div>').text("this is detailsdiv"); ///price of prod
var closebtndiv = $('<div></div>').text("this is closebtndiv");
$('li').append(imgdiv,detaildiv,closebtndiv,"<br>");
$('li').css({'padding':'20px'});
$('div').css({'display':'inline','padding':'20px'});
}
i tried to do this by making a function and run it in for loop..if it works fine then i can call the same function when the data arrives and make a list item.
But some how the o/p of this function is weird.

execute code after selection from dropdown

I am building a meteor based webapp. One of the pages has a drop down menu, which the user has to select options (various school districts) from. The selection needs to be detected, followed by querying the database filtering documents based on the selection and counting the documents returned, followed by rendering a template (a chart built using highcharts.js)
Code as follows:
Template.districtDropdown.events({
'change' : function(event, template){
event.preventDefault();
var selectedValue = template.$("#selectDistrict").val();
console.log("You Selected " + selectedValue);
var filter = {
find: {
'School District' : selectedValue
}
};
Meteor.subscribe('aggByDistrict', filter);
productNames2 = _.uniq(CombinedData.find().map( function(doc) { return doc.Product; }));
console.log(productNames2);
var productValues2 = [];
for(var i = 0; i < productNames2.length; i++) {
productValues2.push(CombinedData.find({'Product' : productNames2[i]}).count())
};
console.log(productValues2);
}
});
I'm facing three issues.
The console on the client side throws an error "productNames2" has not been defined as soon as the page loads, pointing to the line which has the for loop (even before I've made any selection).
The first time I click on one of the options in the drop down menu, I get empty arrays (the two console.log(productNames2) and console.log(productValues2), but when I click on some other option, it works the second time. No idea why.
I want to render a template {{> highchart2}} after the user has selected an option from the drop down and the two arrays (productNames2, productValues2) have been populated.
Can anyone give me ideas on how I can go about resolving these issues?
Several problems with your code
Subscribe needs to be put in Template.districtDropdown.created. If you subscribe during the events, there might be the postpone during the subscription and no data available during the events
event should be attached to a DOM component. As in change #selectDistrict and then, you select the value like this var selectedValue = $(event.target).val();

using razor form and model values instead of current js object

I'm following js snippet to grab value dynamic number of input elements. I then use that values as a property inside js object which I later sent to mvc controller.
Since I already using Model inside razor which already has necessary properties to send to the mvc controller I wonder how can I grab those dynamic input elements values without using javascript object.
var myArr= [];
for (var i = 1; true; i++) {
var pTxtBox = $('#PCaption' + i);
var nTxtBox = $('#PWinners' + i);
if ((pTxtBox).length) {
var myObj = {};
myObj.Name = pTxtBox.val();
myObj.NWinners = nTxtBox.val();
myArr.push(myObj);
} else {
break;
}
}
When you render a page in MVC, The model is populated with whatever you specifically pass into the view. As MVC isn't coupled with the server. The only time the model re-binds is when there is a post back, then it goes through the input fields with the correct 'name' attribute and binds them into the model expected into the HTTPPOST method in the controller.
You will not be able to dynamically get a textboxes value on the client side using razor, Youll have to get the element by id or class, just as you are doing here.

Categories