onclick call to function from submit input not working - javascript

Here is my submit button written dynamically through AJAX:
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
I am trying to rerun the updatefilters() function to change the items that are displayed. I imagine its a bit tough to conceptualize without seeing all the code...but essentially, all I need to do is run the function again on each click of the submit button...right now, its giving me a updatefilters is undefined error in firebug.
Heres my whole JS for reference
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var i = 0;
var page;
if(! page){
page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
});

There appears to be a few problems with this approach.
First, you're not actually calling the function in your onclick handler.
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters;' /></li"
should be:
htmlpage += "<li><input type='submit' value='"+i+"' onclick='updatefilters();' /></li"
Second, the updatefilters function isn't accessible from the global scope, which is where that anonymous function will be executed from. You'd have to move function updatefilters(ev, ui) outside the onload callback, perhaps to the top of your script block.

Related

javascript scripts not working in electron

I am trying to work on electron and made a simple dashboard GUI. i am a beginner in node js and electron.
Problem:
in my main gui.html: i have a table is being loaded, and from that table i need to select the rows from checklist for which i have made a js script:
script in read_checklist.js, this is taking the input checkbox element and selecting the whole row, which will later be shown after some processing in the textarea.
var checkboxes = document.getElementsByTagName("input");
var select_all = document.getElementById("allcb");
var warn_code = Array();
var family_array = Array();
var fail_drive_array = Array();
var waiverMap = {};
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var Warn_Code = currentRow.getElementsByTagName("td")[0];
var Family = currentRow.getElementsByTagName("td")[1];
var failing_drive = currentRow.getElementsByTagName("td")[3];
warn_code.push(Warn_Code.textContent);
family_array.push(Family.textContent);
fail_drive_array.push(failing_drive.textContent);
console.log('server started!' + currentRow );
alert(currentRow.textContent);
};
}
I am trying to import this in my gui.html like this:
This is where the table is getting displayed (code for this is below and it is stored in the renderer.js)
<!--This is for the table-->
<div id="data_lib" class="table-responsive">
</div>
<script type="text/javascript" src="./read_checklist.js"></script>
<!--This is for the table-->
My table is coming from another file, renderer.js
$(document).ready(function(){
var data;
$.ajax({
type: "GET",
url: "/Users/mrimat01/Desktop/CODE/electron_QAB_GUI_main/GUI/data.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
generateHtmlTable(data);
}
});
function generateHtmlTable(data) {
var html = "<table id='big_tables' class='table table-striped table-bordered' method='GET'>";
if(typeof(data[0]) === 'undefined') {
return null;
} else {
$.each(data, function( index, row ) {
//bind header
if(index == 0) {
html += '<thead>';
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<th>';
html += colData;
html += '</th>';
});
html += '<th>';
html += "<input type='checkbox' id='allcb' name='allcb'/>Select";
html += '</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
} else {
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<td>';
html += colData;
html += '</td>';
});
html += '<td>';
html += "<input id='name' type='checkbox' name='name' value='name' /> ";
html += '</td>';
html += '</tr>';
}
});
html += '</tbody>';
html += '</table>';
$('#data_lib').append(html);
}
}
});
I can see the table getting generated but read_checklist.js desn't work.
If i try to do the same thing in console, it works perfectly.
i have gone through many SO answers but couldn't seem to make this work.
Things i have tried:
making node_integration: true
using
module = undefined;}</script>
<script>if (window.module) module = window.module;</script>
adding the script directly below root <div>

manipulate partial view's content with jquery

With the code below I am trying to update PartialView's HTML.
open_Modal_AssignAmendRoles = function (url) {
$.ajax({
url: url,//PartialView URL
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
var modalhtml = data;
var result = datafetchfunction("action URL", )
if (result.compleate == true) {
result.data.employeeroles.forEach(function (roletype) {
var tagbox = $(modalhtml).find("#tagbox" + roletype.clientroletypeid);
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
var roletypeid = roletype.clientroletypeid
roletype.roles.forEach(function (role) {
var roleid = role.FK_ClientRoleID
var roledescription = role.ClientRole_Description;
var rolecode = role.ClientRole_Code
var markup = ""
markup += " <li class='taglist' id='" + roleid + "'>"
markup += " <button onclick='$(this).parent().remove()' class='tagclose'>"
markup += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>"
markup += " </button>"
markup += " <a class='assignedrole' href='Javascript:void(0);' onclick='pop_click_fn(this)'"
markup += " role-id='" + roleid + "' role-type-id=" + roletypeid + ""
markup += " data-toggle='popover' data-trigger='hover' data-content='" + roledescription + "' data-placement='top' > " + rolecode + " </a>"
markup += " </li>";
$(span).append(markup)
})
})
openModal( modalhtml);
}
}
});
}
Step 1:
On button click the open_Modal_AssignAmendRoles() function is called. Then it goes to the success() function.
Step 2:
var result = datafetchfunction("action URL" )
this fetch data as JSON format
Step 3:
Then I start some loop, I already create some spans and find them with
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
Step 4:
then I build a markup and assign this
$(span).append(markup)
and finally, call
openModal( modalhtml);
But modalhtml is not updated as expected, it means lis which I created with loop is not added.
Can someone tell me what is the problem and how to solve this?

jquery added html code not worked

I started new project and I use jquery to add content to article
when I create a slider with this code:
$(".inserttabtext1").click(function () {
var count = parseInt($(".firsttabtextcount").attr("name"), 10);
var name = parseInt($(this).attr("name"));
var id = "#" + name;
var idi,idt,content,idic,idtc;
content = "<div class='short-tabs'><ul>";
for (var i = 1; i <= count; i++)
{
idi = "#ftti" + i;
idic = $(idi).val();
if (i == 1)
{
content += "<li class='active'><a href='#'> " + i + idic + "</a></li>";
}
else
{
content += "<li><a href='#'> "+ i + idic +"</a></li>";
}
}
content += "</ul>";
for (var i = 1; i <= count; i++)
{
if (i==1)
{
content += "<div class='active'>";
}
else
{
content += "<div>";
}
idt = "#fttt" +i;
idtc = $(idt).val();
content += "<p class='text-go-center'>"+idtc+"</p></div>";
}
content += "</div>";
$(id).html(content);
});
and put them into html code my text slider not worked
but when I put manual html code in my page it work
I use these code for copy my html code
$(id).html(content);
$(id).append(content);
where is my wrong?
create a function and put your slider codes inside it, then call it in $(document).ready, and call it again after adding html
$(document).ready(function(){
Init();
});
function Init(){
//Call your slide function here
}
call Init after Adding Html
$(id).html(content);
$(id).append(content);
Init();

IE: jQuery.show() only shows element when using alert() before/after show

I'm trying to add a simple 'wait box' on a javascript function, like this:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working good on Firefox, but not on Internet Explorer 11, that's not showing it. The HTML is:
<div id="ctl00_Wait1_WaitBox" class="updateProgress">
Attendere...<br />
<img src="../Images/wait.gif" align="middle" />
</div>
The weirdest thing is that I try this, for a simple check:
function caricaElenco(indice) {
(...)
alert($("[id*=Wait1_WaitBox]").css('display'))
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert($("[id*=Wait1_WaitBox]").css('display'))
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working, I mean that it's showing the alert with 'none' and after 'block'... And it's showing the box too! But not without the alert... Why?
UPDATE:
Tried with [id*="Wait1_WaitBox"], but it's the same. jQuery version is 1.8.2.
With
it's working only with the alert
I mean that if I do:
function caricaElenco(indice) {
(...)
alert('whatever');
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert('whatever');
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's showing the box, but if I do:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's not working (I mean not showing the 'wait box', but doing all the other stuff the function has to do in (...) correctly—load a gridview with an AJAX call) on Internet Explorer 11, in Firefox are both working. No JavaScript error.
UPDATE 2:
Almost entire javascript function:
// Fill part of gridView
function loadList(index) {
index = parseInt(index);
buffer = 100; // Number of rows to load
$("[id*=divGrid]").unbind('scroll');
$('[id*="Wait1_WaitBox"]').show(); // Show loading 'wheel'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PageName.aspx/webMethodName",
data: '{id:' + $("[id*=hdnID]").val() + ', index:' + index + '}',
dataType: "json",
async: false,
success: function (response) {
if (index == 0) {
(...)
$("[id*=grid] tr:last-child").remove();
var row = "<tr class='" + response.d[index].State + "'>";
row += "<td class="Column1"></td>";
(...)
row += "<td class="DateColumn"></td>";
(...)
row += "<td class='columnN'></td></tr>";
$("[id*=grid]").append(row);
}
row = $("[id*=grid] tr:last-child").clone(true);
$("[id*=grid] tr:last-child").remove();
if (index <= response.d.length) {
if (index + buffer > response.d.length)
var stop = response.d.length;
else
var stop = index + buffer;
(...)
for (var i = index; i < stop; i++) {
var j = 0;
(...)
$("td", row).eq(j).html("<span id='lblCodeNumber" + i + "' >" + response.d[i].CodeNumber + "</span>"); j++;
(...)
var effectDate = new Date(parseInt(response.d[i].effectDate.substr(6)));
$("td", row).eq(j).html(effectDate.getDate() + '/' + (effectDate.getMonth() + 1) + '/' + effectDate.getFullYear()); j++;
}
(...)
var toBeCounted = "";
var checked = "";
if (response.d[i].ToBeCounted != null)
toBeCounted = response.d[i].ToBeCounted .toString();
else
toBeCounted = "true";
if (toBeCounted == "true")
checked = "checked = 'checked'";
else
checked = "";
var rdToBeCounted = "<span><input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='s' id='sToBeCounted" + i + "' />";
rdToBeCounted += "<label for='s" + i + "'>YES</label>";
if (toBeCounted == "false")
checked = "checked = 'checked'";
else
checked = "";
toBeCounted += "<input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='n' id='nToBeCounted" + i + "' />";
rdToBeCounted += "<label for='n" + i + "'>NO</label></span>";
$("td", row).eq(j).html(rdToBeCounted);
$("[id*=grid]").append(riga);
(...)
riga = $("[id*=grid] tr:last-child").clone(true);
}
if (stop < response.d.length) {
$("[id*=divGrid]").scroll(function (e) {
if (element_in_scroll(".congruenti tbody tr:last")) {
loadList($(".congruenti tbody tr:last td:last").html());
};
});
}
$('[id*="Wait1_WaitBox"]').hide();
}
},
error: function (result) {
alert("Error! " + result.status + " - " + result.statusText);
}
});
}
At the end you seem to be hiding it again $("[id*=Wait1_WaitBox]").hide();.
You need to show what goes in between these two lines.
It works with alert because the execution of the script is frozen until you close the alert (and that final line is not executed yet).

Search XML and display results using jQuery

I have multiple XML files which contain TV Listings each file is one TV channel. I want to be able to search by program title and display the results in a html table. So far I have been able to search by one XML file - so by one channel. I want to be able to search by multiple channels using user input via an input box and search button. The XML I have looks like:
<?xml version="1.0" encoding="UTF-8"?>
<channel id="sky_one" source="Sky" date="25/11/2014">
<programme>
<desc>Tony's motorcycle bursts into flames between his legs while town planner Liz is left in agony after her half-tonne horse bolts and lands on top of her. Also in HD</desc>
<title>The Real A & E</title>
<end>0630</end>
<start>0600</start>
</programme>
(only a snippet)
The jQuery that I have so far, which works for one channel looks like:
$(document).ready(function () {
//GLOBAL VAR
var keyword = '';
var pub = '';
var i = 0;
$("#searchButton").click(function () {
keyword = $("input#term").val();
//Reset any message
var errMsg = '';
pub = '';
if (keyword == '') {
errMsg += 'Please enter a search term';
} else {
searchThis();
}
if (errMsg != '') {
pub += '<div class="error">';
pub += errMsg;
pub += '</div>';
}
//Show error
$('#result').html(pub);
});
// ----------------------------------------- SKY NEWS -----------------------------------------------------------
function searchThis() {
$.ajax({
type: "GET",
url: "https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_one.xml",
dataType: "xml",
success: function (xml) {
loadPublication(xml)
}
});
}
function loadPublication(xmlData) {
i = 0;
var row;
var searchExp = "";
$(xmlData).find('programme').each(function () {
var title = $(this).find('title').text();
var desc = $(this).find('desc').text();
var start = $(this).find('start').text();
//Format the keyword expression
var exp = new RegExp(keyword, "gi");
//Match to Title of programme
searchExp = title.match(exp);
if (searchExp != null) {
//Start building the result
if ((i % 2) == 0) {
row = 'even';
} else {
row = 'odd';
}
i++;
pub += '<tr class="row ' + row + '">';
pub += '<td valign="top" class="col1">' + title + '</td>';
pub += '<td valign="top" class="col2">' + desc + '</td>';
pub += '<td valign="top" class="col3">' + start + '</td>';
pub += '</tr>' + 'n';
}
});
if (i == 0) {
pub += '<div class="error">';
pub += 'No Result was Found';
pub += '</div>' + 'n';
//Populate the result
$('#result').html(pub);
} else {
//Pass the result set
showResult(pub);
}
}
function showResult(resultSet) {
//Show the result
pub = '<div class="message">There are ' + i + ' results!</div>';
pub += '<table id="grid" class="table-bordered">';
pub += '<thead><tr>' + 'n';
pub += '<th class="col1"> </th>';
pub += '<th class="col2">Title</th>';
pub += '<th class="col3">Desc</th>';
pub += '<th class="col4">Start</th>';
pub += '</tr></thead>';
pub += '<tbody>';
pub += resultSet;
pub += '<hr class="horule" />';
pub += '</tbody>';
pub += '</table>';
//Populate
$('#result').html(pub)
}
});
And the html is as follows:
<input type="text" id="term" placeholder="Search by program title..."></div>
</div>
<input type="button" id="searchButton" value="Search" class="btn btn-primary" />
<div id="result"> </div>
I had an the idea of using the xml files as variables then using .when and .then to utilize the xml files, although I am not quite sure how to implement these, something like:
// Open the xml file
var sky1 = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_one.xml',
bbc1 = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/bbc1.xml',
skyn = 'https://scm.ulster.ac.uk/~B00533474/workspace/COM554/assignment_2/CR/sky_news.xml';
$.when(
$.ajax( sky1 ),
$.ajax( bbc1 ),
$.ajax( skyn )
).then(function( skyone, bbcone, skynews ) {
var sky1p = $(skyone).find('programme'),
bbc1p = $(bbcone).find('programme'),
skynp = $(skynews).find('programme');
//sky one
sky1p.each(function() {
//DO Search
//sky one
skynp.each(function() {
//DO Search
//sky one
bbcp.each(function() {
//DO Search
The intended output is a html table with the title, description and program time. If anyone could help that would be great!

Categories