JavaScript does not change element style - javascript

I have Quiz partialview and I use severeal of them inside Index.cshtml. I want to change style of partialview elements on button click. I send ids to function as a parameter. Though I successfully get elements, I can't change their style. Do you have any solution please?
Index.cshtm:
#model IEnumerable<QuizIt_Tests.Entities.Quiz>
#{
ViewData["Title"] = "Index";
}
<link rel="stylesheet" href="~/css/QuizCard.css">
<link rel="stylesheet" href="~/css/DeleteButton.css">
#{
for (var i = 0; i < 10; i++)
{
foreach (var quiz in Model)
{
Html.RenderPartial("EditorTemplates/Quiz", quiz);
}
}
}
<script>
function DeleteClick(DeleteButtonId, SpanId, SVGId) {
var DeleteButton = document.getElementById(DeleteButtonId);
console.log(DeleteButton);
DeleteButton.style.width = "150px";
DeleteButton.style.height = "50px";
DeleteButton.style.transition = ".3s";
console.log(DeleteButton);
var DeleteButtonSpan = document.getElementById(SpanId);
DeleteButtonSpan.style.opacity = "1";
DeleteButtonSpan.style.transition = ".3s";
var DeleteButtonSVG = document.getElementById(SVGId);
DeleteButtonSVG.style.opacity = "0";
DeleteButtonSVG.style.transition = ".3s";
}
function DeleteMouseLeave(DeleteButtonId, SpanId, SVGId) {
var DeleteButton = document.getElementById(DeleteButtonId);
console.log(DeleteButton);
DeleteButton.style.width = "50px";
DeleteButton.style.height = "50px";
DeleteButton.style.transition = ".3s";
console.log(DeleteButton);
var DeleteButtonSpan = document.getElementById(SpanId);
DeleteButtonSpan.style.opacity = "0";
DeleteButtonSpan.style.transition = ".3s";
var DeleteButtonSVG = document.getElementById(SVGId);
DeleteButtonSVG.style.opacity = "1";
DeleteButtonSVG.style.transition = ".3s";
}
</script>
Quiz.cshtm:
#model QuizIt_Tests.Entities.Quiz
#{
ViewData["Title"] = "View";
var DeleteButtonId = "deletebutton" + Model.Id;
var SpanId = "deletebuttonspan" + Model.Id;
var SVGId = "deletebuttonsvg" + Model.Id;
}
<div class="tile">
<div class="quizdiv">
<h2>#Model.Name</h2>
<div class="quizdiv2">
<p class="m-0 pt-4">Teacher: Samir Osmanov</p>
<p class="m-0">Deadline: 21.01.2022</p>
</div>
</div>
<div class="overlay">
<button id="#DeleteButtonId" onclick='DeleteClick("#DeleteButtonId","#SpanId", "#SVGId" )' onmouseleave='DeleteMouseLeave("#DeleteButtonId","#SpanId", "#SVGId" )'>
<span id="#SpanId">CONFIRM DELETE</span>
<svg id="#SVGId" width="25" height="25" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
Quiz Class:
public class Quiz{
[Key]
public Guid Id { get; } = Guid.NewGuid();
public string Name { get; set; }
public ICollection<Question> Questions { get; set; } = new List<Question>() { };
public Quiz()
{
}
public Quiz(ICollection<Question> questions)
{
Questions = questions;
}
}

Related

MVC: Razor: Bind SelectList's SelectedValue to textbox

I have a model and a View with a select and a few text boxes. I am trying to bind the textbox values to the selected list item the following way:
Model:
public class Items
{
public string ID { get; set; }
public string Name { get; set; }
public SelectList ItemList { get; set; }
public List<SelectListData> MiscList { get; set; }
}
public class SelectListData{
public string ID { get; set; }
public string Name { get; set; }
public string Address{get; set;}
public string City{get; set;}
public string State{get; set;}
}
Controller:
Controller:
public async public async Task<IActionResult> Index()
{
Items viewModel = new Items();
List<SelectListData> tempLIst = new List<SelectListData>();
tempLIst.Add(new SelectListData() { ID = "1", Name = "ID-1", Address="123 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "2", Name = "ID-2", Address="234 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "3", Name = "ID-3", Address="345 AVE", City = "New City", State = "CA"});
tempLIst.Add(new SelectListData() { ID = "4", Name = "ID-4", Address="456 AVE", City = "New City", State = "CA"});
viewModel.ItemList = new SelectList(tempLIst, "ID", "Name", 2);
viewModel.SelectListData = tempLIst;
return View(viewModel);
}
View:
#Model Items
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control" onchange="OnSelectedIndexChanged_01(this)"></select>
</div>
#{
if(Model.ID != null) {
var selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ID).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" /> =====? how do I set the value to selectedAddress here?
</div>
</div>
</div>
<script>
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList()); ===? this is being assigned correctly
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out
//myArray = jsdata;
console.log("[" + selectedID + "] [" + jsdata + "] [" + myArray + "]"); ===> this line is printing [[object, object], [object, object], [object, object]]
//console.log("[" + selectedID + "] [" + jsdata + "]");
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].ID == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].Address.toString();
break;
}
}
}
</script>
I am trying to bind the selectedValue of the dropdown to a selected Address. Any help is appreciated.
Edit:
As ScareCrow indicated, I am able to bind the initial values.
ANother question: my javascript doesn't seem to populate the address text based on the OnChange event of the dropdownlist. I am not sure if I am passing the model's arraylist properly. Any pointers is helpful.
Thanks
NH
Please try the following code Snippet in view: made changes in your code
#model Items;
#{var selectedAddress=string.Empty;}
<div class="form-group">
<label class="col-lg-2 control-label">Account</label>
<div class="col-lg-10">
<div class="input-group col-lg-10">
<span class="input-group-addon">
<i class="fa fa-globe" aria-hidden="true"></i>
</span>
<select asp-for="ID" asp-items="#Model.ItemList" class="form-control"></select>
</div>
#{
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
}
<div>
<input id="selAddress" value="#selectedAddress" />
</div>
</div>
</div>
I believe the selected items you set in
if(Model.ItemList != null) {
selectedAddress = Model.MiscList.SingleOrDefault(c => c.ID == Model.ItemList.SelectedValue.ToString()).Address;
}
rather than Model.ID in your code.
Dropdown change event can be achieved by the following Javascript code snippet:
$(document).ready(function () {
$('#ID').change(function () {
var selectedValue = $(this).val();
var misclist = #Json.Serialize(#Model.MiscList.ToList());
for(i=0;i<misclist.length;i++){
if(misclist[i].id == selectedValue) {
$('#selAddress').val(misclist[i].address);
break;
}
}
});
});
There were 2 issues with my question. #ScareCrow provided a solution to my first issue and helped me in figuring out the solution to my second issue. Here's an updated javascript function(with the key values being lower-case):
function OnSelectedIndexChanged_01(value, jsdata) {
var selectedID = value.options[value.selectedIndex].value;
var selectedText = value.options[value.selectedIndex].text;
var myArray = [];
var jsdata = #Json.Serialize(#Model.MiscList.ToList());
//myArray = JSON.parse(jsdata); ===> this line throws "Unexpected token o in JSON at position 1"; commenting this worked out; jsdata is already a javascript object
myArray = jsdata;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].id == selectedID) {
var Address = document.getElementById("selAddress");
Address.value = "";
Address.value = myArray[i].address.toString();
break;
}
}
}

If condition on event listeners

I would like to use the addEventListener as a condition
so that if the condition is true by the clicking of the
image, the code executes, but it doesn't seem to work.
HTML
<div class = "content">
<img src = "dog.png" alt = "" id = "firstImage" >
<img src = "coatOfArm.png" alt = "" id = "second
Image" >
<p id = "score" >0</p>
</div>
JavaScript
var firstImage =
document.getElementById("firstImage");
var secondImage =
document.getElementById("secondImage");
var score= document.getElementById("score");
var totalScore_1 = 0;
var totalScore_2 = 0;
firstImage.addEventListeners("click",function() {
totalScore_1++;
score.innerHTML = totalScore_1;
})
secondImage.addEventListeners("click", function() {
totalScore_2++;
score.innerHTML = totalScore_2;
})
function increScore() {
if(first Image clicked == true){
firstImage. append(score) ;
} else{
secondImage. append(score) ;
}
} ;
increScore() ;

Angular : Display data item stored in an array one by one

I've a simple situation, where I've a bunch of data stored in an array.
I want to display the array in html view, one by one, when the next/prev buttons are clicked.
I followed this : How to show item from json Array one by one in Angular JS
However, My code doesn't seem to work.
Code :
/**
* Created by PBC on 5/21/2016.
*/
var solver = angular.module('solver', []);
solver.controller('data', data);
function data($scope, $http){
$scope.Type = "";
$scope.qlist = [];
$scope.alist = [];
$scope.idx = 0;
$scope.ans = "";
$scope.q = "";
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
var data = $.param({
_Down_Questions:localStorage.getItem('prb')
});
$http.post("../Php/download_questions.php", data, config).then
(
//Success Callback
function (res) {
$scope.Type = res.data.Type;
if ($scope.Type == 'Objective'){
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"]};
$scope.qlist[i] = data;
}
}
else{
for(var i = 0; i < res.data.Data.length; i++){
var data = {Q:res.data.Data[i]["Q"], A:res.data.Data[i]["A"], O:res.data.Data[i]["O"]};
$scope.qlist.push[i] = data;
}
}
},
//Error Callback
function () {
$scope.registrationResponse = "";
swal("Request couldn't be sent!", "", "error");
}
);
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
$scope.prev = function () {
if ($scope.idx > 0){
$scope.idx -= 1;
ans = $scope.alist[$scope.idx];
}
};
}
using this, in the html as :
<div data-ng-controller="data">
<div style="display: table;margin: 0 auto; width: 30%">
<div class="row container" style="margin-top: 50%">
<div class="col l12" data-ng-repeat="q in qlist track by $index" data-ng-show="$index == idx">
{{q[idx]["Q"]}}
</div>
<input placeholder="Answer" data-ng-model="ans" type="text" class="validate center">
<div class="row" style="display: table;margin: 0 auto; width: 100%">
<a class="waves-effect waves-light btn" data-ng-click="next()" style="display: table;margin: 0 auto; width: 50%">Next</a><br>
<a class="waves-effect waves-light btn" data-ng-click="prev()" style="display: table;margin: 0 auto; width: 50%">Previous</a>
</div>
</div>
</div>
</div>
What am I doing wrong ?
I've found the mistakes:
1)
{{q[idx]["Q"]}}
should be
{{q["Q"]}}
2)
$scope.next = function () {
if ($scope.idx < res.data.Data.length){
$scope.alist[$scope.idx] = $scope.ans;
$scope.idx += 1;
$scope.ans = null;
}
};
Here, the condition was wrong :
it should be,
if ($scope.idx < $scope.qlist.length){

Angular JS indefinite execution of a function called inside a ng-repeat

I am building an app using google's QPX express and I created a service to call the QPX web service.
I noticed that when I inspect certain functions, I see that they are executing indefinitely. The functions are $scope.pageArray, $scope.humanizeTime.Can someone help me identify why this is the case.
I have an understanding of why this is happening, but am not able to identify the root cause. Somehow/Somewhere in the code I am suggesting to Angular that the model has changed and therefore Angular is running a $scope.$digest, but I cant seem to identify where.
var resultController =planeSearchControllers.controller('resultController',['$scope','$http','commonSharedService','flight', function($scope,$http,commonSharedService,flight){
var isDebugEnabled = true;
$scope.showResults = false;
$scope.showPlaneSearch = true;
$scope.showPlaneError = false;
$scope.planeView = false;
$scope.historyView = false;
$scope.$watch(function() {return commonSharedService.getMode();},function(newValue,oldValue){
console.log('New Mode is' + newValue);
if(newValue == 'plane'){
$scope.planeView = true;
$scope.historyView = false;
$scope.historyObj = [];
}else if(newValue == 'history'){
getHistory(commonSharedService.getUserName());
$scope.planeView = false;
$scope.historyView = true;
}
});
$scope.$watch(function (){return commonSharedService.getValidateInputs();},function (newValue,oldValue){
if(isDebugEnabled){
console.log('Value is changed for getValidateInputs ' + 'New Value is -->'+ newValue);
}
$scope.validateInputs = newValue;
if($scope.validateInputs == true) {
makePlaneCall();
$scope.showResults = true;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
if($scope.validateInputs == false) {
$scope.showResults = false;
commonSharedService.setValidateInputs(undefined);
$scope.errorMsg = commonSharedService.getErrorMsg();
}
});
$scope.humanizeTime = function(time){
//var duration = new moment.duration(time, "minutes");
//var hours = duration.hours();
//var minutes = duration.minutes();
var hours = Math.floor(time/60);
var minutes = time - (60 * hours);
var str = hours == 0 ? '': hours + 'hours ' ;
str += minutes == 0 ? '': minutes + 'minutes';
return str;
};
//Page Filtering
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.numPages = function () {
if($scope.tripOption!=null )
return Math.ceil($scope.tripOption.length / $scope.numPerPage);
else
return 0;
};
$scope.pageArray = function () {
var input = [];
for(var i=0;i<$scope.numPages();i++){
input[i] = i+1;
}
return input;
};
var paging = function(arrayIn,pageNo,perPageNo){
var outArray = [];
if(arrayIn!=undefined){
var from = perPageNo * (pageNo-1);
var to = from + perPageNo;
if (to > arrayIn.length)
to= arrayIn.length;
//console.log(from);
//console.log(to);
//console.log(outArray);
for (var i =from; i<to ;i++)
outArray.push(arrayIn[i]);
}
return outArray;
};
$scope.paginationFilter = function (){
return paging($scope.tripOption,$scope.currentPage,$scope.numPerPage);
};
var makePlaneCall = function () {
$scope.appendObj = commonSharedService.getAppendObj();
$scope.jsonObj = commonSharedService.getJsonObj();
$scope.jsonObj['time'] = moment().format("ddd Do,YYYY HH:mm a");
var user = commonSharedService.getUserName();
if(user != undefined)
setHistory(user,$scope.jsonObj);
$scope.planeRequest = {};
$scope.requestObj = {};
var slice = [];
var slice1 ={};
var slice2 ={};
var slice3 ={};
{
slice1['origin'] = $scope.appendObj['departAirport'];
slice1['destination']= $scope.appendObj['multiCity'] ? $scope.appendObj['interimAirport'] :$scope.appendObj['arrivalAirport'];
slice1['date']= $scope.appendObj['departureDate'];
slice1['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['departureEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice1['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice1);
}
if($scope.appendObj['multiCity'] == true){
slice2['origin'] = $scope.appendObj['interimAirport'];
slice2['destination']= $scope.appendObj['arrivalAirport'];
slice2['date']= $scope.appendObj['interimDate'];
slice2['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['interimEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice2['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice2);
}
if($scope.appendObj['isReturnFlight'] == 'true'){
slice3['origin']=$scope.appendObj['arrivalAirport'];
slice3['destination'] = $scope.appendObj['departAirport'];
slice3['date']=$scope.appendObj['arrivalDate'];
slice3['permittedDepartureTime'] ={
"earliestTime": $scope.appendObj['arrivalEarliest']
};
if($scope.appendObj['preferredCabin']!=undefined){
slice3['preferredCabin'] = $scope.appendObj['preferredCabin'];
}
slice.push(slice3);
}
for(var property in $scope.jsonObj){
if($scope.jsonObj.hasOwnProperty(property)){
$scope.requestObj[property] = $scope.jsonObj[property];
}
}
$scope.requestObj['slice'] = slice;
//$scope.requestObj['passengers'] = $scope.jsonObj['passengers'];
$scope.requestObj['solutions'] = 5;
$scope.requestObj['refundable'] = false;
$scope.planeRequest['request'] =$scope.requestObj;
flight.search($scope.planeRequest,function(response){
$scope.result= response;
$scope.info = $scope.result.trips.data;
$scope.tripOption = $scope.result.trips.tripOption;
//console.log($scope.tripOption);
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
}
}
else{
$scope.showPlaneError = true;
$scope.planeSearchErrorMsg = "No Solutions found. Please check your airport codes and set more liberal parameter for the search to see if something turns up.";
}
console.log(response);
},function(response){
console.log("error");
$scope.result= response;
console.log(response);
});
};
function setHistory(userName,historyObj){
var firstTime=true;
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var historyRef = ref.child(userName);
historyRef.on("value", function(historySnapshotObj) {
if(firstTime==true){
var historySnapshot = historySnapshotObj.val();
console.log(historySnapshot);
var count;
if(historySnapshot!=null)
count = historySnapshot['count'];
console.log(count);
var obj ={};
if(count == undefined) {
obj['count'] = 0;
obj[0]= historyObj;
}else if(count < 9){
obj['count'] = ++count;
obj[count]= historyObj;
}else if(count == 9){
console.log(3);
obj['count'] = count;
for(var i=0;i<9;i++)
obj[i+1] = historySnapshot[i];
obj[0] = historyObj;
}
firstTime = false;
historyRef.update(obj);
}
else {
console.log("Wrong Place");
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
function getHistory(userName){
var ref = new Firebase("http://flight-searchdb.firebaseIO.com/History");
var usersRef = ref.child(userName);
usersRef.on("value", function(snapshot) {
for (var i=0;i<10;i++){}
var userHistory = snapshot.val();
var count;
var array=[];
if(userHistory!=null)
count = userHistory['count'];
if (count!=undefined) {
for (var i=0;i <count ; i++)
array.push(userHistory[i]);
}
$scope.historyObj = array;
$scope.$digest();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
}]);
I tested all functions and all of them seem to be working , except that when I added the pagination I dont see any result.
P.S : I was using a filter before , but for the sake of debug , I moved the pagination logic into the controller. I also understand that I could have used a directive.(since I am displaying the result at only place, I decided to skip it.)
I am also adding the view below , in which I am using the controller.
<!-- Result Body-->
<div class="col-sm-6 col-md-6 col-lg-7" data-ng-controller="resultController">
<div class="container-fluid">
<div data-ng-show="planeView">
<div data-ng-hide="showResults">
<div><span></span><span>{{errorMsg}}</span></div>
</div>
<div data-ng-show="showResults">
<div class="showPlaneSearch" data-ng-show="showPlaneSearch">
<div class="query thumbnail">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<span >Page</span>
<select data-ng-model="currentPage" id="selectPage" class="form-control col-xs-5 col-sm-5 col-md-5 col-lg-5"
data-ng-options="value for value in pageArray()" data-toggle="popover" data-trigger="hover" data-placement="right"
data-content="Select Page Number">
</select>
</div>
</div>
</div>
<ul class="planesResult">
{{currentPage}}
{{numPerPage}}
<li ng-repeat="trip in paginationFilter" class="thumbnail">
<div class="row phoneContents">
<!-- Image -->
<div class="hidden-xs hidden-sm hidden-md col-lg-2">
<img src="images/Airplane-Icon.png" />
</div>
<!-- Trip Total $$$ -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10" >
<span class="price">{{trip.saleTotal}}</span>
</div>
<!-- Everything except Image -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<!--Each Slice -->
<div ng-repeat="slice in trip.slice" class="slice row">
<!-- Each Segment Origin-->
<span class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-repeat="segment in slice.segment">
<span > {{segment.leg[0].origin}}--></span>
<span ng-show="$last"> {{segment.leg[0].destination}} </span>
</span>
</span>
<!-- Each Segment Origin-->
<span class="col-xs-12 col-sm-3 col-md-3 col-lg-3">{{humanizeTime(slice.duration)}}</span>
<span ng-repeat="segment in slice.segment" class="col-xs-hidden col-sm-4 col-md-4 col-lg-4">
<span ng-show="$first"> Depart at {{}} </span>
</span>
<br>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="showPlaneError" data-ng-show="showPlaneError">
<span class="thumbnail">{{planeSearchErrorMsg}}</span>
</div>
</div>
</div>
<div data-ng-show="historyView">
<pre>{{historyObj | json}}</pre>
</div>
</div>
</div>
I can't run code, but i see something suspicious, worth changing:
two places:
$scope.paginationFilter = function (){
return paging($scope.tripOption,
and
if($scope.tripOption!=null){
{
$scope.airport = $scope.info.airport;
$scope.city = $scope.info.city;
$scope.aircraft = $scope.info.aircraft;
$scope.tax = $scope.info.tax;
$scope.carrier = $scope.info.carrier;
$scope.showPlaneError = false;
$scope.paginationFilter();
I see that when tripOption!= null you call paginationFilter function, which uses tripOption.

How to access gridview cell value with javascript

I have a javascript function that I am trying to validate the inputs of a gridview. My problem is that I cannot get the value of the cell. Here is what I have:
function fcnCheck() {
var grid = document.getElementById("<%= GridViewProducts.ClientID %>");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++) {
cellPivot = grid.rows[i].cells[0];
cellStatus = grid.rows[i].cells[1];
if (cellPivot == "Yes" and cellStatus == "") {
alert("You must select an answer for all columns if Pivot is yes")
return false;
}
}
}
}
This line does not work: cellPivot = grid.rows[i].cells[0];
Most likely you want (edit)
var theDropdown = grid.rows[i].cells[0].elements[0];
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?
http://aspdotnetcodebook.blogspot.com/2010/01/how-to-get-cell-value-of-gridview-using.html#comment-form
Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";
});
$("#listAge").html(list)
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},
};
return list;
}
}
<script language="javascript" type="text/javascript">
function Calculate()
<br/>
{
<br/>
var grid = document.getElementById("<%=GridID.ClientID%>");
<br/>
var sum = 0; <br/>
for (var i = 1; i < grid.rows.length; i++)<br/>
{ <br/>
var Cell = grid.rows[i].getElementsByTagName("input");
<br/>if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[4].value);} }
<br/>
document.getElementById("<%=TextBox1.ClientID%>").value = sum;
}
<br/>
</script>
------------------------------------------------------------------------
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="cridnvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="CalculateTax();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>
//your gridview id in my case my gridview is named dgd and the id comes from
// ClientID
var myGrid = document.getElementById("<%= dgd.ClientID %>");
var oRows = myGrid.rows;
var k;
for (k = 1; k < oRows.length; k++)
{
var currentRow = myGrid.rows[k];
//now you can see the 1st,2nd and 3trd column value
alert(currentRow.cells[1].innerHTML);
alert(currentRow.cells[2].innerHTML);
alert(currentRow.cells[3].innerHTML);
}
function rowWisegetcellvalueingridview() {
///concat string
var str1 = "";
var n = document.getElementById('hdnColumn').value;
///concat string
var grid = document.getElementById('GridView1');
var Inputs = grid.getElementsByTagName('input');
var Inputsa = grid.getElementsByTagName('a');
var Inputsspan = grid.getElementsByTagName('span');
var Input = Inputs.length;
var j = 0;
var p = 0;
var r = 0;
for (t = 0; t < grid.rows.length - 1; t++) {
var HdnID1 = Inputs[j].value;
var HdnID2 = Inputs[j + 1].value;
var HdnID3 = Inputs[j + 2].value;
var HdnID4 = Inputs[j + 3].value;
var HdnID5 = Inputsa[p].innerHTML;
var HdnID6 = Inputsa[p + 1].innerHTML;
var HdnID7 = Inputsspan[r].innerHTML;
var varConcat = "(" + HdnID1 + "," + HdnID2 + "," + HdnID3 + "," + HdnID4 + "," + HdnID5 + "," + HdnID6 + "," + HdnID7 + "),\n";
n = n.concat(varConcat);
j = j + 4;
p = p + 2;
r = r + 1;
}
return false;
}

Categories

Resources