ASP.NET - Jquery to add textbox and dropdown list dynamically - asp.net

I need to be able provide a table on web page with one row which has a two drop down list and one textbox and the user's should be able to add any number of rows they want. I need to to this using jquery so that i can avoid post back. Is this possible to be done in Jquery and if it is possible i was looking for some example which will be like a pointer

This should get you started... save as a .html file for an example
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function createTextbox(){
return "<input type='text' />"
}
function createDropDown(){
return "<select><option>One</option><option>Two</option><option>Three</option></select>"
}
function createRow(){
return "<tr><td>" + createTextbox() + "</td><td>" + createDropDown() + "</td><td>" + createDropDown() + "</td></tr>";
}
function getValuesForPostback(){
//format as XML, JSON, or Whatever
var ToReturn = "<items>";
$('#sampleTable tr').each(function(){
ToReturn += "<item>";
//Get the textbox value
ToReturn += "<text>" + $(this).find('input[type=text]').val() + "</text>";
//Get the select values
$(this).find('select option:selected').each(function(){
ToReturn += "<select>" + $(this).val() + "</select>";
});
ToReturn += "</item>";
});
ToReturn += "</items>";
return ToReturn;
}
function submitValues()
{
alert(getValuesForPostback());
//NOW: Just ajax or post back this value to the server and parse for your data.
}
$(document).ready(function(){
$('#sampleTable').append(createRow());
$('#btnAdd').click(function(){
$('#sampleTable').append(createRow());
});
$('#btnSubmit').click(function(){
submitValues();
});
});
</script>
</head>
<body>
<table id="sampleTable">
</table>
<button id="btnAdd">Add</button>
<button id="btnSubmit">Submit</button>
</body>
</html>

Related

aria-autocomplete / typeahead not auto selecting

I have implemented aria-autocomplete and twitter/bloodhound typeahead.
Problem: It is partially working in the sense that it retrieves the value, but I want it to be automatically selected.
When I type in a Member ID, I want it to automatically select the name in a div below, and in a hidden textbox (which is later checked if there is a value, before allowing user to go to next screen)
What I've tried:
I have read the following:
https://msdn.microsoft.com/en-us/ie/hh968240(v=vs.94)
https://www.w3.org/TR/wai-aria-practices/examples/combobox/aria1.1pattern/listbox-combo.html
I then changed "aria-autocomplete": "list" to "both" as well as "inline" and neither had an affect.
I then changed my textbox from autocomplete off to autocomplete on with no effect:
I then read about typeahead, but I am not understanding why the autocompleted is not having an affect either. Here is the code for that:
.
displayKey: function (item) { return item.Subscriber_ID },
templates: {
//Template to show if there are no results
empty: function (context) {
// console.log(1) // put here your code when result not found
$(".tt-dataset").text('No Results Found');
},
suggestion: function (item) {
return '<div class=""> ' + item.First_Name + " " + item.Last_Name + '</div>';
}
}
})
.
I resolved this by adding some code to the suggestion function, to add a TextBox that the c# should look at , instead of having it look at it after the click:
$('#suggestionName').val(item.First_Name + " " + item.Last_Name); //used to check whether there is a value when hitting submit (hidden field)
$('#divDisplayMemberName').html(item.First_Name + " " + item.Last_Name); //displays it in a <p> tag underneath the TextBox
return '<div class=""> ' + item.First_Name + " " + item.Last_Name + '</div>'; //displays the actual suggestion

How to add hyperlink inside ClientTemplate with IF condition- Ajax Bound Kendo UI for ASP.NET MVC

I am using ASP.NET MVC. I want to make the Account_Number column as HTML link in the Ajax Bound Kendo UI grid, when it is not searched by Account_Number from previous page. And when clicked on the Account_Number link, it should pass the Account_Number to the Customer controller method 'QuickCheckSearch'.
The below code does not populate the grid in view and also do not call/pass the value to the controller. Could someone please correct the following code?
Thanks in Advance.
columns.Bound(p => p.Account_Number)
.ClientTemplate("<#if (item.Account_Number == Model.AccountNumber){>Account_Number <# }" + "else{#><a href='" + Url.Action("QuickCheckSearch", "Customer") + "?Account_Number=#=Account_Number#'>#= Account_Number #</a> <# } #>")
.Title("Account Number");
Read http://docs.telerik.com/kendo-ui/framework/templates/overview
You have way too many angle brackets all over the place. You should only have them on the actual HTML markup of the template, not as part of the template syntax itself. Try:
.ClientTemplate(
"# if (Account_Number ==" + #Model.AccountNumber + "){ #" +
"#= Account_Number #" +
"# }" +
"else { #" +
"<a href = '" + Url.Action("QuickCheckSearch", "Customer") + "?Account_Number=#=Account_Number#'>#= Account_Number#</a>" +
"# } #"
)
I find it really helps to format it on separate lines just like you would write actual code instead of all on one line so you can see the structure visually.
You could also do it this way, which may be cleaner:
.ClientTemplate("#= accountLinkTemplate(data) #")
....
<script>
function accountLinkTemplate(data) {
var template = data.Account_Number;
if (data.Account_Number == " + #Model.AccountNumber + ") {
template = "<a href = '" + "#Url.Action("QuickCheckSearch", "Customer")" + "?Account_Number=" + data.Account_Number+ "'>" + data.Account_Number+ "</a>";
}
return template;
}
</script>

Youtube api running fine with html, incorrectly with aspx

I'm relatively new with aspx and just tried to start moving my html page with youtube api with javascript into visual studio and aspx in order to move data into a database. In html the page seems to work fine and the next page button will successfully pass the pageToken. However, when I moved my html code to aspx, I noticed the page seems to refresh and drops my next page token, reloading the same front page. It also gives me a warning code that only occurs in aspx and not the html:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
Setting 'XMLHttpRequest.withCredentials' for synchronous requests is deprecated.
I am not adding any scripts using my jquerys, which I believe is the main cause of this warning. My nextPage function however does recall the api for additional requests.
In terms of moving the html to aspx all I do is copy all my html code and put it into the header and body respectively. Am I missing a step in migrating? Do I have to change my code when using aspx instead of html?
Here is my current ASPX page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="JavaScript1.js"></script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
<style type="text/css">
#courses {
width: 566px;
}
.auto-style1 {
width: 556px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="video-container">
<table><tr>
<td class="auto-style1">
<h1> Rutgers Accounting Digital Library Directory </h1>
</td>
<td align="right"><div id="summary"></div></td>
</tr>
<tr><td class="auto-style1"><form action="search_results.asp" method="Post"><input type="text" name="search1" placeholder="Search Here" size="20"><input type="Submit" name="Submit" value="Submit"></form></td><td><form method="link" action="my_uploads.html" ><input type="Submit" name="Clear" value="Clear Filters"></form></td></tr>
<tr><td colspan="2">
<form>
<select id="courses" onchange="show()">
<option selected disabled>Select a Course</option>
</select>
</form>
</td></tr>
<div class="button-container">
<tr>
<td class="auto-style1"><button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button></td>
<td align="right"><button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button></td>
</tr>
<tr>
<table id="results"></table>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
Here is my javascript page:
// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken, status, cid;
var totalr = 0;
var rpp = 0;
var sum;
var dur = '';
function onClientLoad() {
gapi.client.load('youtube', 'v3', handleAPILoaded);
}
// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
gapi.client.setApiKey('APIKEY');
requestUserUploadsPlaylistId();
}
// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
// See https://developers.google.com/youtube/v3/docs/channels/list
var request = gapi.client.youtube.channels.list({
part: 'contentDetails',
forUsername: 'rutgersweb'
});
request.execute(function (response) {
cid = response.result.items[0].id;
dropdown(cid);
playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
requestVideoPlaylist(playlistId);
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
console.log(pageToken);
$('#results').html('');
console.log(pageToken);
var requestOptions = {
playlistId: playlistId,
part: 'snippet',
maxResults: 50
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function (response) {
totalv = response.pageInfo.totalResults;
rrp = response.pageInfo.resultsPerPage;
sum = '<td>Results Per Page: ' + rrp + '</td><td>Total Pages: ' + Math.ceil(totalv / rrp) + '<td>Total Videos: ' + totalv + '</td>';
$(sum).replaceAll('#summary');
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#next-button').css('visibility', nextVis);
$('#next-button2').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#prev-button').css('visibility', prevVis);
$('#next-button2').css('visibility', nextVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function (index, item) {
displayResult(item.snippet);
});
} else {
$('#results').html('Sorry you have no uploaded videos');
}
});
}
function getVideoDetails(mmp, ddp, yyyyp, dur, vidId, videoTitle, used) {
var request = gapi.client.youtube.videos.list({
part: 'contentDetails',
id: vidId
});
request.execute(function (response) {
var str = JSON.stringify(response.result.items[0].contentDetails.duration);
str = str.replace(/"/g, "");
str = str.replace(/PT/g, "");
str = str.replace(/H/g, ":");
str = str.replace(/M/g, ":");
str = str.replace(/S/g, "");
str = str.split(':');
var ftime;
if (str[1] < 10) {
ftime = str[1];
str[1] = '0' + ftime;
}
if (str[2] < 10) {
ftime = str[2];
str[2] = '0' + ftime;
}
displayOutput(mmp, ddp, yyyyp, str, vidId, videoTitle, used);
});
}
// Create a listing for a video.
function displayResult(videoSnippet) {
var videoTitle = videoSnippet.title;
var videoId = videoSnippet.resourceId.videoId;
var videoDescription = videoSnippet.description;
var videoPub = videoSnippet.publishedAt;
//dur =
//PublishedAt Formatting to compare
ar3 = videoPub.split("T");
uselessd = ar3[0];
re = new RegExp("-", "g");
uselessd2 = uselessd.replace(re, "/");
usedd = uselessd2.split("/");
ddp = usedd[2];
mmp = usedd[1];
yyyyp = usedd[0];
//Description trimming to leave time stamps only
ar = undefined;
useless = undefined;
useless2 = undefined;
used = undefined;
ar2 = undefined;
ar = videoDescription.split("Time Stamps:");
useless = ar[0];
useless2 = ar[1];
if (useless2 != undefined) {
ar2 = useless2.split("Summary");
ar = ar2[0];
re = new RegExp("\n", "g");
useless = ar.replace(re, "<br>");
used = useless;
}
else
used = " ";
// outputArray=[mmp, ddp, yyyyp, dur, videoId, videoTitle,used]
// displayOutput(outputArray);
getVideoDetails(mmp, ddp, yyyyp, dur, videoId, videoTitle, used)
}
function displayOutput(mmp, ddp, yyyyp, dur, videoId, videoTitle, used) {
//output = '<tr><td colspan="3" align="right">Published On: '+oarray[0]+'/'+oarray[1]+'/'+oarray[2]+'<br>'+dur+'</td></tr><tr><td><img src="http://img.youtube.com/vi/'+oarray[4]+'/1.jpg"></img></td><td>'+oarray[5]+'</td></tr><tr><td colspan="2" align="right">'+oarray[6]+'<hr>';
if (dur[2])
output = '<tr><td colspan="3" align="right">Published On: ' + mmp + '/' + ddp + '/' + yyyyp + '<br>Length: ' + dur[0] + ':' + dur[1] + ':' + dur[2] + '</td></tr><tr><td><img src="http://img.youtube.com/vi/' + videoId + '/1.jpg"></img></td><td>' + videoTitle + '</td></tr><tr><td colspan="2" align="right">' + used + '<hr>';
else
output = '<tr><td colspan="3" align="right">Published On: ' + mmp + '/' + ddp + '/' + yyyyp + '<br>Length: ' + dur[0] + ':' + dur[1] + '</td></tr><tr><td><img src="http://img.youtube.com/vi/' + videoId + '/1.jpg"></img></td><td>' + videoTitle + '</td></tr><tr><td colspan="2" align="right">' + used + '<hr>';
//Append to results listStyleType
$('#results').append(output);
}
// Retrieve the next page of videos in the playlist.
function nextPage() {
console.log(nextPageToken);
requestVideoPlaylist(playlistId, nextPageToken);
}
// Retrieve the previous page of videos in the playlist.
function previousPage() {
requestVideoPlaylist(playlistId, prevPageToken);
}
function dropdown(cid) {
var requestOptions = {
channelId: cid,
part: 'snippet',
maxResults: 50
};
var request = gapi.client.youtube.playlists.list(requestOptions);
request.execute(function (response) {
var plists = response.result.items;
if (plists) {
$.each(plists, function (index, item) {
var drp = document.getElementById("courses");
var optn = document.createElement("OPTION");
optn.text = item.snippet.title;
optn.value = item.id;
drp.add(optn);
});
} else;
});
}
function show() {
var e = document.getElementById('courses');
var txt = e.options[e.selectedIndex].value;
requestVideoPlaylist(txt);
}
I know the code is a little messy, still trying to get better coding habits, and I should probably fix some useless variables.
Set the type="button" on your button controls to prevent them from submitting the page each time they are pressed:
For example, in your ASPX page use:
<td class="auto-style1"><button type="button" id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button></td>
<td align="right"><button type="button" id="next-button" class="paging-button" onclick="nextPage();">Next Page</button></td>

Getting Information from Console.log and displaying it in div

Currently I am stuck I want to return the title, plot and poster using themoviedb api I have no idea how to start the coding for this
Currently when i run a search the information is display in the console log of the browser i want to take that information and style it into a table format nothing fancy just the title and poster need help no clue where to start
doc site here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie',
input,
movieName,
key = '?api_key=My API KEY HERE';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<body>
<input id="movie" type="text" /><button>Search</button>
</body>
</html>
output looks like this it returns objects under a movie title in his chase 300
error when running each staement
Something like this:
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.original_title + '</td><td>' + value.release_date + '</td></tr>';
});
table += '</table>';
$('.myelement').html(table);
}
});
You don't read from the console. It's just for outputting debug information. The AJAX call basically returns an JavaScript object (whose structure you can see in the the console).
Access the data from it just like from any other JavaScript object (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects if you need to learn how) and work with that.
EDIT: If you need to know how to display the data on the web page, you need to learn about the DOM. See for example: http://www.elated.com/articles/javascript-dom-intro/

Form within a form and a JSON call

In my page I have a form:
<form method="post" id="confirm-order-form" name="confirm-order-form">
Inside the form I have written some scripts to make a JSON call:
<script type="text/javascript"><xsl:text disable-output-escaping="yes"><![CDATA[
$(function() {
$('#submit').click(function() {
if ($('#nlapproved').attr('checked')) {
newsletter();
}
});
function newsletter()
{
$form = $('<form action="http://mydomain.createsend.com/t/j/s/jtes/" method="post" id="subForm" />');
$form.append('<input type="hidden" name="cm-name" id="hidName" />');
$form.append('<input type="hidden" name="cm-jtes-jtes" id="hidEmail" />');
$form.append('<input type="hidden" name="cm-fo-pikty" id="hidPrivateBusiness" />');
$form
.find("#hidName")
.val(']]></xsl:text><xsl:value-of select="$context//checkoutinformation/info[key='name']/value" disable-output-escaping="yes"/><xsl:text disable-output-escaping="yes"><![CDATA[');
$form
.find("#hidEmail")
.val(']]></xsl:text><xsl:value-of select="$context//checkoutinformation/info[key='email']/value" disable-output-escaping="yes"/><xsl:text disable-output-escaping="yes"><![CDATA[');
$form
.find("#hidPrivateBusiness")
.val(']]></xsl:text><xsl:value-of select="$acctype"/><xsl:text disable-output-escaping="yes"><![CDATA[');
$.getJSON(
$($form).get(0).action + "?callback=?",
$($form).serialize(),
function (data) {
if (data.Status === 400) {
alert("Error: " + data.Message);
} else {
// 200
alert("Success: " + data.Message);
}
}
);
}
});
]]>
</xsl:text>
</script>
My problem is that this thing does not work when the outer form is there--the code works fine otherwise.
Note: I am redirecting this page to another physical server in the post back of my outer form and i have a lot of other controls in my first form so i cant simply avoid that.
Can anyone help?
The actual form is being submitted. Stop that:
$("#confirm-order-form").on('submit', function (e) { e.preventDefault(); });
EDIT: to submit ajax, then normal form:
...ajax.done(function () {
$("#confirm-order-form").off('submit').trigger('submit');
});
After successful ajax completion, unbind the prevention of the form submission and trigger a submission.
1) Add a div outside the form that has the runat="server" attribute.
<form runat="server">
<!-- stuff here -->
</form>
<div id="target"></div>
2) Write your jQuery selector to target that div.
$('#target').append('<form id="newform"></form>');
// add your controls...
$.post(
'your_action',
$('#newform').serialize(),
function(result){
// handle result...
},
'json');
3) Do whatever you need to do with the server form...

Resources