I'm a C/C++ programmer and new to javascript. The following code is giving me grief and I don't really know what I'm doing wrong. I've searched and can't find where others have had the same problem.
I've taken my project and cut out my problem code to try and understand and fix it. The short version is when I click my "Enter data" image on an HTML page, it creates a dialog box with a form and table of inputs (with default data) and I enter/change some data. When I click the dialog box save button, it goes through JSON.stringify($('#form').jsonify()) to collect the form data and brings up an alert box showing the data that I entered. This part works fine.
If I click the "Enter data" image again, the dialog box comes up and I enter/change new data. When I click the dialog box save button, it brings up an alert box showing the previous data that I saved (in this case showed in the alert box).
No matter how many times I try it, it always returns the data form the very first entry and never any of the new(er) data.
What am I doing wrong?
Some references:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="~/Scripts/test.js"></script>
<link href="~/Content/jquery/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" />
My HTML code
<div>
<img id="additem"
Title="Add Item"
onclick="addstuff(this)"
OnMouseOver="this.style.cursor='pointer';"
OnMouseOut="this.style.cursor='default';"
src="~/images/Sign_Add_Icon_32.png" />
</div>
My test.js file.
$.fn.jsonify = function (options) {
var settings = $.extend({
stringify: false
}, options);
var json = {};
$.each(this.serializeArray(), function () {
if (json[this.name]) {
if (!json[this.name].push)
json[this.name] = [json[this.name]];
json[this.name].push(this.value || '');
} else
json[this.name] = this.value || '';
});
if (settings.stringify)
return JSON.stringify(json);
else
return json;
}
function addstuff(obj) {
var strHtml = "";
var strHtml = "<div class=\"container\" id=\"addphonedlg\" title=\"Add Phone\" overflow:\"auto\">"
+ "<p>Please enter the following information.</p>"
+ "<form id=\"form\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 1" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data1" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 1 data" + "\" />" + "</td></tr>"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 2" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data2" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 2 data" + "\" />" + "</td></tr>"
+ "<tr><td align=\"right\"><label for=\"name\">" + "Data 3" + ":</label></td>"
+ "<td><input type=\"text\" name=\"" + "data3" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 3 data" + "\" />" + "</td></tr>"
+ "</table></form>"
+ "</div>";
$(strHtml).dialog({
autoOpen: false,
width: 400,
modal: true,
buttons: {
"Save": function () {
alert("Add information " + JSON.stringify($('#form').jsonify()));
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
}
}).dialog('open');
}
This seems to be a known problem of forms in ui dialogs being cached. But you need to remove the form onClose of the dialog.
I added close event function to your code. You should be fine now.
$(strHtml).dialog({
autoOpen: false,
width: 400,
modal: true,
close: function( event, ui ) {
$('#form').remove(); // this where the problem is
},
buttons: {
Save: function () {
alert("Add information " + JSON.stringify($('#form1').jsonify()));
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
}
}).dialog('open');
}
Related
I got a so far as good working youtube api data v3 search script but i was so in trouble with this script since days i think im blind it works and paginates everytime 2 entries. But there must be a failure in the js or html code should be easy but i cant figure out please help me. Demo Link is aviable under
Artist search Battle Rap Net Youtube Search
This is the Code so far i used please take a look at the demo link to understand the problem.
The Js Code:
var nextPageToken, prevPageToken;
var firstPage=true;
$(document).ready(function()
{
$('#searchbutton').click(function()
{
// Called automatically when JavaScript client library is loaded.
// alert('i am clicked');
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
// Called automatically when YouTube API interface is loaded .
// Called automatically with the response of the YouTube API request.
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page"+nextPageToken+"</button></div>");
});
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page "+prevPageToken+"</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page "+nextPageToken+"</button></div>");
$('#nextPageButton').click(function()
{
// alert('i am clicked');
console.log(nextPageToken);
searchYouTubeApi(nextPageToken);
});
$('#prevPageButton').click(function()
{
// alert('i am clicked');
console.log(prevPageToken);
searchYouTubeApi(prevPageToken);
});
});
function onYouTubeApiLoad()
{
// See to get a key for your own applications.
gapi.client.setApiKey('MYAPICODE');
searchYouTubeApi();
}
function searchYouTubeApi(PageToken)
{
var searchText= $('#searchtext').val();
//$('#response').append("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
$('#response').replaceWith("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
// Use the JavaScript client library to create a search.list() API call to Youtube's "Search" resource
var request = gapi.client.youtube.search.list(
{
part: 'snippet',
q:searchText,
maxResults:2,
pageToken:PageToken
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
// $('#response').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page return from request execute method is: "+nextPageToken+"</button></div>");
}
function onSearchResponse(response)
{
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken=response.nextPageToken;
prevPageToken=response.prevPageToken;
// document.getElementById('response').innerHTML += responseString;
//$('#response').append("<div id=count><b>Found "+resultCount+" Results.</b></div>");
$('#count').replaceWith("<div id=count><b>Found "+resultCount+" Results.</b></div>");
//$('#searching').append("<div id=length><b>Length "+response.items.length+" </b></div>");
for (var i=0; i<response.items.length;i++)
{
//store each JSON value in a variable
var publishedAt=response.items[i].snippet.publishedAt;
var channelId=response.items[i].snippet.channelId;
var title=response.items[i].snippet.title;
var description=response.items[i].snippet.description;
var thumbnails_default=response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium=response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high=response.items[i].snippet.thumbnails.high.url;
var channelTitle=response.items[i].snippet.channelTitle;
var liveBroadcastContent=response.items[i].snippet.liveBroadcastContent;
var videoID=response.items[i].id.videoId;
//var firstPage=true;
// console.log(thumbnails_default);
//A HTTP call to this URL with videoID will give all XML info of that video:
//http://gdata.youtube.com/feeds/api/videos?q=videoID
// console.log(videoID);
//replace the first search button with a 'more' button
//$('button').replaceWith("<button type='button' id=More"+i+">More...</button>");
if(firstPage===true)
{
//print the stored variables in a div element
$('#snipp').append("<div id=T><b>Title:</b> "+title+"</div><div id=C><b>Channel ID: </b>"+channelId+"</div><div id=D><b>Description </b>"+description+"</div><div id=P><b>Published on: </b>"+publishedAt+"</div><div id=CT><b>Channel Title: </b>"+channelTitle+"</div><a id=linktoVid href='http://www.youtube.com/watch?v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
else
{
$('#T').replaceWith("<div id=T><b>Title:</b> "+title+"</div>");
$('#C').replaceWith("<div id=C><b>Channel ID: </b>"+channelId+"</div>");
$('#D').replaceWith("<div id=D><b>Description </b>"+description+"</div>");
$('#P').replaceWith("<div id=P><b>Published on: </b>"+publishedAt+"</div>");
$('#CT').replaceWith("<div id=CT><b>Channel Title: </b>"+channelTitle+"</div>");
$('#linktoVid').replaceWith("<a id=linktoVid href='http://www.youtube.com/watch v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
// $('#snipp').append("<div id=C"+i+">Channle ID: "+channelId+"</div><br/>");
//link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=76TlUlPZQfQ&feature=youtube_gdata'/>
}
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage=false;
}
The HTML:
<body>
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp">
<div id=T0
</div>
<br/><br/><br/>
</body>
After create a jsfiddle with your code, I could check the pagination is working correctly.
The problem you're facing lies in your HTML code (most specific: in how you're building your HTML code).
My humble advice is that "instead of using append", re-creates the HTML that renders the current page.
Also, just after all controls loaded in the screen, the "prevPageButton" and "nextPageButton" buttons shows undefined.
For this situation, change these lines:
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
For this:
if (prevPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
}
if (nextPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
}
After a few modifications, you can check here the updated and working jsfiddle.
The tl;dr version is as follows:
Logic for build the HTML code was replaced for set a variable that (in the for-loop) builds the HTML code.
At the end of the loop, the HTML is added directly to the div container called "snipp".
Removed other HTML unneccesary code.
This is the modified code:
HTML:
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp"></div>
JS:
function onSearchResponse(response) {
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken = response.nextPageToken;
prevPageToken = response.prevPageToken;
$('#count').replaceWith("<div id=count><b>Found " + resultCount + " Results.</b></div>");
// This variable will save the HTML code in construction.
var HTML_CONTENT = "";
for (var i = 0; i < response.items.length; i++) {
//store each JSON value in a variable
var publishedAt = response.items[i].snippet.publishedAt;
var channelId = response.items[i].snippet.channelId;
var title = response.items[i].snippet.title;
var description = response.items[i].snippet.description;
var thumbnails_default = response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium = response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high = response.items[i].snippet.thumbnails.high.url;
var channelTitle = response.items[i].snippet.channelTitle;
var liveBroadcastContent = response.items[i].snippet.liveBroadcastContent;
var videoID = response.items[i].id.videoId;
// Buld the HTML to render at the current page.
HTML_CONTENT += "<div id='video_item'> " +
" <div id=T><b>Title:</b>" + title + "</div> " +
" <div id=C><b>Channel ID: </b>" + channelId + "</div> " +
" <div id=D><b>Description </b>" + description + "</div> " +
" <div id=P><b>Published on: </b>" + publishedAt + "</div> " +
" <div id=CT><b>Channel Title: </b>" + channelTitle + "</div> " +
" <a id='linktoVid' href='http://www.youtube.com/watch?v=" + videoID + "'><img id='imgTD' src='" + thumbnails_default + "' /></a><br/><br/><a id='linktoVid1' href='http://www.youtube.com/watch?v=" + videoID + "'><video id='vidTD' width=\"320\" height=\"240\" controls poster='" + thumbnails_default + "'><source src='http://www.youtube.com/watch?v=" + videoID + "'>Your browser does not support the video tag.</video></a><br/><br/> " +
"</div>";
}
// Post all HTML generated code (built in the previous for-loop).
document.getElementById('snipp').innerHTML = HTML_CONTENT;
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage = false;
}
I need to add my captcha in a pop up but there are some stuff that need to be handled.
first of all as i get the captcha from back-end its a php class,
and secondly i need to add the object in an external js script,
so far i assigned the object to a variable in my blade file as below:
<script>
var captchaVar = '{!! NoCaptcha::display() !!}'
</script>
and for pop up I have the following code in my script file
.confirm({
title: 'Confirm!',
content: '<div class="col-xs-12">\n' +
'<div class="cr-item">\n' +
'<label class="inl-blk">security code</label>\n' +
'<div class="inp area inl-blk">\n' +
+ captchaVar + '\n' +
'</div>\n' +
'</div>\n' +
'</div>',
buttons: {
confirm: function () {
$(this).submit();
},
cancel: function () {
}
}
});
I get NaN instead of captchaVar which should be
<div class="g-recaptcha" data-sitekey=""></div>
.confirm({
title: 'Confirm!',
content: '<div class="col-xs-12">\n' +
'<div class="cr-item">\n' +
'<label class="inl-blk">security code</label>\n' +
'<div class="inp area inl-blk">\n' +
captchaVar + '\n' +
'</div>\n' +
'</div>\n' +
'</div>',
buttons: {
confirm: function () {
$(this).submit();
},
cancel: function () {
}
}
});
There was a plus too much in your code. It then created the NaN instead of the expected result.
I have a Kendo mvc Grid and using client template as a column and i wrote a javascript function in the template to return the script block but its seems not working and no javascript error. I also tried to write the script to the client template directly but its not working too.
//html in client template
.Columns(columns =>
{
columns.Template(e =>
{ }).ClientTemplate(
"<div class='table-responsive'>" +
"<table border='0' class='table' >" +
...................................
"</table>" +
"</div>"+
"#=AlignDiv(Id)#"
);
})
//javascript function to return a script block as a string
<script type="text/javascript">
function AlignDiv(Id) {
var result = "<script> $('.calDiv"+Id+"').map(function () {" +
"return $(this).Height();" +
"}).get()," +
"maxHeight = Math.max.apply(null, heights);" +
"$('.calDiv" + Id + "').height(maxHeight);" +
"alert('test')<\/script>";
return result;
}
Thanks a lot,
Dennis
In order to format Kendo Grid Column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName)
.Title("Status Name")
.Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#").Width("55px");
...
Javascript Method:
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>
I use this js-code in my programm http://jsfiddle.net/yeyene/JyfPg/1/ and it works just fine on fiddle. In my programm it's working on every second click. I'm loading the data for the People from a xml file in a partial view.
On the first click I get an empty space below the Person and on the second it fills with the information I want. When I clik on a second Person it first close the open one (which it shouldn't, as I want to have the same behaviour as in the fiddle) and then it opens the content from the last open one until I click again and then it updates...
My js:
$(document).on("click", "#btnPeople", function () {
if ($("tr#" + $(this).data("href")).is(":visible")) {
$("tr#" + $(this).data("href")).remove();
}
else {
var peopleCallID = $(this).attr("data-id");
var urlDetails = siteRoot + peopleID + "/peopleDetails";
$("#peopleInfos").load(urlDetails);
$(this).closest("tr").after("<tr id='" + $(this).data("href") + "'> <td colspan='5'>"
+ $("#" + $(this).data("href")).html() + "</td> </tr>");
}
});
My html:
<button class="btn btn-default btn-sm active show" id="btnPeople" data-href="peopleInfos" data-id="#item.ID">
Details </button>
I'm sitting on this now for quiet a while,
first my js wouldn't work, so I had to change it from
$(function () { $("#btnPeople").click("click", function () {
to
$(document).on("click", "#btnPeople", function () {
I'm really new to javascript and jquery, so I'm sorry if there is an easy answer to this.
I already got rid of all extra scripts and style sheets, so there is no conflict there.
And tried :
$(document).ready(function() {
$(document).on("click", "#btnPrintAgent", function() {
Appreciate every hint you can give me.
EDIT: Problem solved!
I changed my code to :
$(document).on("click", "#btnPeople", function () {
if ($("tr#" + $(this).data("href")).is(":visible")) {
$("tr#" + $(this).data("href")).remove();
}
else {
var peopleCallID = $(this).attr("data-id");
var urlDetails = siteRoot + peopleID + "/peopleDetails";
$(this).closest("tr").after("<tr id='" + $(this).data("href") + "'> <td colspan='5'>"
+ $("#" + $(this).data("href")).html() + "</td> </tr>");
$("#peopleInfos").load(urlDetails);
}
});
and now it's loading like it should.
By changing
$("#peopleInfos").load(urlDetails);
into
$("#"+peopleCallID).load(urlDetails);
and setting my html to
<button class="btn btn-default btn-sm active show" id="btnPeople" data-href="#item.ID" data-id="#item.ID">
Details </button>
everything works as I wanted.
Thanks for all the help and getting me in the right direction!
function load() give you a trigger after load is performed. http://api.jquery.com/load/
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
so your code should be:
$(document).on("click", "#btnPeople", function () {
if ($("tr#" + $(this).data("href")).is(":visible")) {
$("tr#" + $(this).data("href")).remove();
}
else {
var peopleCallID = $(this).attr("data-id");
var urlDetails = siteRoot + peopleID + "/peopleDetails";
$("#peopleInfos").load(urlDetails, function() {
$(this).closest("tr").after("<tr id='" + $(this).data("href") + "'><td colspan='5'>" + $("#" + $(this).data("href")).html() + "</td> </tr>");
});
}
});
Not completely sure, but if I'm not wrong, the .load() function work "asyncronous", thus, when after it you call
$(this).closest("tr").after("<tr id='" + $(this).data("href") + "'> <td colspan='5'>"
+ $("#" + $(this).data("href")).html() + "</td> </tr>");
The data are not fetched yet, thus you're working with old data.
Try change the two lines like this, adding a callback funciton to be called after the load function complete
$("#peopleInfos").load(urlDetails, function() {
$(this).closest("tr").after("<tr id='" + $(this).data("href") + "'> <td colspan='5'>"
+ $("#" + $(this).data("href")).html() + "</td> </tr>");
});
I need to output a variable I have within a readonly formfield (text):
$(function() {
return $("#buy_order_btn").click((function(_this) {
return function() {
var price;
price = $("#order_bid_price").val();
return bootbox.dialog({
title: "Confirm Buy Order",
message: "Price: <input type=\"text\" readonly=\"readonly\" value=\"HERE COMES THE PRICE VALUE FROM ABOVE\">"
});
};
})(this));
});
How to do this?
$(function() {
return $("#buy_order_btn").click((function(_this) {
return function() {
var price;
price = $("#order_bid_price").val();
return bootbox.dialog({
title: "Confirm Buy Order",
message: "Price: <input type=\"text\" readonly=\"readonly\" value=\"" + price + "\">"
});
};
})(this));
});
I would consider using ' when I have html inside the string, just so it can be readable as a normal html text