JQuery/Javascript how to Parse HTML using a Get - javascript

I have the following working code. This displays a drop down and also fetches a html file to be displayed:
$.getJSON('json/shares.json', function(data) {
var items = [];
$.each(data.Shares, function(key, val) {
items.push('<option id="' + val.shareID+ '">' + val.shareID+ '</option>');
});
$('<select/>', {
'id': 'shares',
html: items.join('')
}).appendTo('#shares');
});
</script>
<script type="text/javascript">
$.get('lon_shares.html', function(data){
$(data).appendTo('#shares');
});
</script>
I need to amend this to a few extra things.
Firstly, I need the drop down to auto submit when a choice is made.
I then need it to get the html file relevant to the choice, for example if they choose the "FML" option it will get the html file "FML_shares.html" if they choose "GBP" then it should get "GBP_shares.html" and finally if the choice doesn't have any html file related to it then an error should be displayed such as "no such file" etc.
Just to make it a little more complex, I don't want the whole file. The file has a table in it and I want to get the data from the first row of the table, for the first five columns of data and display those alone.
Thanks for any assistance, I've been searching for a solution for a while without any success and my JQuery/Javascript knowledge is very basic! (I've done something similar with PHP in the past but that's not an option here)

Well for the first point you could just run
$('#shares').on('change', function(){
var val = $(this).val();
//submit another ajax request with this value, and get the relevant page, then you'd just need to parse it for the appropriate content from that page.
});
If you want to parse the returned page and get only part of this we'd need to know the markup structure.

Seems like you just need to bind to the .change event of the dropdown you are creating to do the submission, which you can retrieve with .get. You can use jQuery to parse the html. It does a nice job of that:
.appendTo('#shares')
.change(function () {
$.get($(this).val() + '_shares.html)
.done(function (html) {
var $table = $(html).find("table tr:first td").slice(0,5);
})
.fail(function () { /* no such file */ });
});
This code is untested, but hopefully you can follow the example. Also beware of GET caching.

Related

how to pass parameter while including file in jsp using tag

i have one jsp page(addStep1.jsp) where i have lot of input fields and drop downs to get values from user.
among all the dropdowns i want to get value from one of the drop down whose id is svoAffectedSoftware.
<select id="svoAffectedSoftware" name="svoAffectedSoftware" class="form-control" >
Now, on the same page i want to include other jsp file for which i have uses below code (i have uses two approach to solve this but in both the cases i am not getting the desire output. the problem in first approach is i am not getting any error but my page doesn't comes up not even my addStep1.jsp where i have included this code and in the second approach it saying:: The method $(String) is undefined for the type
__2F_ssappmgr_2F_webapps_2F_sam_2F_apps_2F_itapp_2F_ticket_2F_addStep1_2E_jsp. )
approach 1
<%# include file="ticketResolutionChatBot.jsp?svoAffectedSoftware="svoAffectedSoftware %>
or
approach 2
<jsp:include page="ticketResolutionChatBot.jsp" >
<jsp:param name="svoAffectedSoftware" value="<%= $("#svoTicketState").val() %>"/>
</jsp:include>
can anyone tell me how do i pass parameter in the correct way also how to achieve this?
I would like to suggest you to use javascript for this purpose. With jQuery it is very easy to achieve your goal.
Include jQuery library in your jsp page
Example is here https://www.w3schools.com/jquery/jquery_get_started.asp
And here: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_lib_microsoft
Don't forget to use all your jquery code inside
$(document).ready(function(){
// your code for the page
});
use my example for you from fiddle
https://jsfiddle.net/u0frjksd/3/
This function subscribes to your select value and loads content page, based on the selection:
$(".form-control").on('change', function() {
var value = $(this).val();
$('.content').load(value);
});
Instead of first value you can provide your own value, I mean your href(in value) to the jsp page you want to include.
Your jsp page will be loaded to the div .
i have uses change() and ajax function here.
$('#svoAffectedSoftware').change(function() {
var form_data = {
svoAffectedSoftware: $("#svoAffectedSoftware").val()
};
$.ajax({
type: "GET",
cache: false,
url: "getNewPage.jsp",
data: form_data,
success: function(data){
$("#contentDiv").html(data);
}
});
});
where, url: "getNewPage.jsp"--> redirecting page,
var form_data = {svoAffectedSoftware: $("#svoAffectedSoftware").val()}; --> takes value for the new page which i was asking through parameter,
success: function(data){$("#messageDiv").html(data);} --> include the content of the resultant page into original page (addStep1.jsp) in the specified div.

Javascript Help on Dropdown filter

I was able to find a solution on Stackoverflow that display HTML "li" elements based on a filter (see attachement). Essentially based on css class'es defined in HTML elements, it populates the drop down list that you can select from.
I would like to be modify javascript below so that when you navigate to one of the "li" elements pages (as seen here: https://jsfiddle.net/quwfmepL/2/ e.g. Note: Chose one Test1 element and it goes to the page1.html page) ..but when you hit the back button on the page1.html to page where filter resides, it doesn't remember last filter choice. As it does now, you are required to filter same choice again. I think what I need to do is look at the browser history, but not sure if there is an easier option. I was hoping it could be in the format of query string or like.
<script type="text/JavaScript">
$(document).ready(function() {
var $tagList = $('#tag-list'),
optionArr = [];
$("#demo-list li a").each(function(index, item) {
$.each($(this).attr('class').split(' '), function(i, option){
if ($.inArray(option, optionArr) == -1) {
$tagList.append('<option value="'+option+'">'+option.replace('-', ' ').replace('_', ' ')+'</option>');
optionArr.push(option);
}
});
});
// Look at the URL for filter and modify here #
$tagList.on('change', function() {
var selection = $tagList.val();
if (selection == "all") {
$('#demo-list li a').show();
} else {
$('#demo-list li a').hide();
$('#demo-list li a.'+selection).show();
}
});
});
</script>
Any suggestions or hints? Any help is appreciated.
Fiddle is acting a bit strangely (not working) for me.
You may want to just set a cookie inside of the .change function, that'd probably be the easiest way to do it. When the filter page loads, check to see if the cookie is set, and if it is, run the filter based on the stored cookie value.
Try out: https://github.com/js-cookie/js-cookie
Alternatively, and probably even better, you can use webstorage (localstorage) to accomplish the same thing.
http://www.w3schools.com/html/html5_webstorage.asp

How to give runtime paging to tables in mvc3.net

I am creating the runtime table in mvc3.net. From controller i am getting the json collection and in view am creating the runtime table according to json collection
first am just initialising the table
<div id="DisplayBookChapterList" class="fLeft per30 mr15">
<table class="contentTable" id="tblDisplayChapterList" >
</table>
In Runtime am populating the table rows by below given code
$.getJSON("#Url.Action("GetBookChapterList", "CourseManagement")" + '/' + bookname, function (data) {
$.each(data, function (key, val) {
BookChapterlist += '<tr><td style="display:none" id=ChapterListBookID value=' + val.BookID + '>' + val.BookID + '</td><td>' + val.ChapterNo + ' </td><td>' + val.Title + '</td><td><input type=checkbox id="' + val.ChapterID + '"></td></tr>';
}
});
$('#DisplayBookChapterList table').append(BookChapterlist);
I want to give paging to this dynamically created table.
You'll want to create the paging links to select a specific page, next, previous, first, last or whatever you need. E.g.
<ul>
#foreach (var page in Enumerable.Range(1, numPages)) {
<li>#Html.ActionLink(page.ToString(), "GetBookChapterList", "CourseManagement", new {page}, new {#class = "page-link"})</li>
}
</ul>
Note that all links have the css class "page-link".
On the server side, add a "page" parameter to your action so you know which page to fetch in the controller.
Now, back to the HTML code: the href of each link is the address where to fetch the data from and we can use this in our JavaScript code:
<script>
$(function() {
$(".page-link").on('click', function(e) {
e.preventDefault();
$.getJSON($(this).attr('href'), function(data) {
console.log(data);
});
});
});
</script>
The nice thing about this approach is that you can make it easily fall back for clients that have JavaScript disabled: in the "GetBookChapterList" action, check if the request is an ajax request (Request.IsAjaxRequest()). If so, return the required JSON data. If not, render a normal, full page showing the selected page of the table.
This is generally a good approach: if possible, make sure the site works without JavaScript, then add JavaScript to improve it.
Add an optional 'Page' parameter to your GetBookChapterList action method and make GetBookChapterList return data for that page. If you use entity framework, use the Skip and Take methods on IQueryable to implement the paging.
In the browser, render next/previous page links at the bottom of the table that gets and re-renders the data for the next/previous page.

Passing parameters to jQuery function via link

I have a jQuery function:
$(function(){
function InitDialog(c,b){
/* some code */
}
$('a[name=dialog]').click(function(e) {
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
And also I have a link defined in html code like below:
<ul>
<li>something</li>
</ul>
My question is how can I pass the parameters (caption, bodyText) to Init() function via link?
I've heard about some method like below:
<li>something</li>
But I don't understand how can I get and parse it?
Thanks
Since you are using jquery, I would recommend that you do the following to store data on your element
Link Text
Then in your click function, you can access it as shown below
$('a#dialog').click(function(){
var me = $(this), data = me.data('params');
//console.log(data);
});
Edit - Fiddle added
Check the fiddle to see a working sample
using data-* attribute, you can:
<a name='dialog'
data-caption='this is the caption'
data-bodytext='this is the body'>klik</a>
and the javascript:
$(function() {
function InitDialog(c, b){
alert('the caption: ' + c);
alert('the body: ' + b);
}
$('a[name=dialog]').click(function(e) {
caption = $(this).data('caption'); // gets data-caption attribute value
bodyText = $(this).data('bodytext'); // gets the data-bodytext attribute value
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
tho instead of using name as the selector, i'd recommend class instead
So first, I think you want to say $('a[href="#dialog"]') to get the a tags, then in the click function, $(this).attr("name") will give you the some information, which you could store a json string...
My Text
$('a[href="#dialog"]').click(function() {
var data = JSON.parse($(this).attr("name"));
InitDialog(data.caption, data.bodyText);
});
But, I don't think that's the right way of going about what you're trying to do, would you be better to create the dialog in a div lower down the page, hide it, and only show it when you click the link? Because the term 'bodyText' implies it's going to be big...
Or just:
My Link

How can I send POST data and navigate with JQuery?

On my blog I have a lot of <pre> blocks containing code snippets.
What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.
I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.
The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.
I have a feeling the solution is dead simple and probably obvious, I just can't think of it.
Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.
Using dialogs with jQuery UI:
$('pre').on('click', function() {
$('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
... set up dialog parameters ...
});
});
Build a form
$('pre').on('click', function() {
var text = $(this).text();
$('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
.appendTo('body');
$('[name="code"]').val(text);
$('.hidden-form').submit();
});
You could use a hidden <form> element. Then set the onclick() attribute of the <pre> to copy the value from the <pre> to the form. Optionally, you can set the action attribute to select the page you'd like to post the information to. Finally, submit that form.
I know it's not elegant, but it'll work.
If your code snippets are stored somewhere in a database or files, I suggest you just link the snippets to a page where you get the snippet based on some identifier.
If the snippets are only contained in your html, and you just want to display them in a cleaner way, you shouldn't need any ajax posting. You might want to Use a hover div or a jquery plugin, that pop's up and shows a cleaner piece of code obtained from the pre element, something like:
$('pre').click(function() {
var code = $(this).html(); //this is the pre contents you want to send
$('#hoverDiv').html(code).show();
});
Yes, you have to create a form and submit it. You can do all sorts of things with ajax posts/gets but the only way to navigate to a post result is via an actual form post. Here is concise version of it:
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();
My code does this:
// Navigate to Post Response, Convert first form values to query string params:
// Put the things that are too long (could exceed query string limit) into post values
var form = $('#myForm');
var actionWithoutQueryString = form[0].action.split("?")[0];
var action = actionWithoutQueryString + '?' + $.param(form.serializeArray());
var html = myArray.map(function(v, i) { return "<input name='MyList[" + i + "]' value='" + v + "'/>"; }).join("\n");
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();

Categories

Resources