Switch span text using JQuery in a table - javascript

I have a table generated from a program, listing info from a database. You can see it here:
http://www.homeducate.me/cgi-bin/browseTutors.cgi?Lui=en&countryCode=MO
For one piece of text, if it's long, I'm listing a shortened version of the text.
Now I'd like to switch it to the longer version when the user clicks on the row to expand some other rows below.
My table has a set of repeating sections like this:
<tr class="header">
//some stuff
<script>
var approachTxt1 = "Shortened version of the text...";
var approachFullTxt1 = "Full length version of the text to be displayed.";
</script>
<td><img src="an_image.png"><span id="approach1">Shortened version of the text...</span><img src="another_image.png"></td>
//some more stuff
</tr>
<tr>Some more rows of stuff</tr>
Then I use the following script to (1) initially collapse all the rows up under each header row, (2) toggle them to display again when a header row is clicked (3) redirect to a url if the user clicks on the un-hidden rows and (4) change the pointer to a mouse when over the table. It all works nicely.
<script>
$('#listTutors .header').each(function () {
$(this).nextUntil('tr.header').toggle();
});
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
});
});
$("tr:not('.header')").click(function () {
top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
});
$('html,table').css('cursor','pointer');
</script>
Now what I wanna do is switch the shortened version of the text to the full text when the user clicks to expand that section, and then switch it back to the shortened form once again when the user clicks again to hide that section. I've been trying:
$(this).next('span').html($(this).next('span').html() == approachTxt1 ? approachFullTxt1 : approachTxt1);
But I'm getting "undefined is not a function" and "unexpected string" errors. Its clearly not picking up the span after the current header.
Plus I'm struggling to think how can I actuate this change for each set of my table rows (eg. switch the appropriate strings out according to which header row the user picks). I've been scratching my head on this for too long :( and would really appreciate any guidance.
Any help much appreciated.
Cheers.

Ok, finally worked out how to do it. Posting here just in case it might help someone else in the future....
First, I set a unique id for each section of my table:
<tr class="header" id="$nnn">
where $nnn is driven from my Perl program and is simply 1,2,3 etc.
Then for each section of the table, I put the short and long text strings into elements of an array:
<script>
approachTxt[$nnn] = "short version of the text";
approachFullTxt[$nnn] = "long version of the text which will be switched in and out";
</script>
Then my script becomes:
<script>
$('#listTutors .header').each(function () {
$(this).nextUntil('tr.header').toggle();
});
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
});
$('#span' + this.id).html($('#span' + this.id).html() == approachTxt[this.id] ? approachFullTxt[this.id] : approachTxt[this.id]);
});
$("tr:not('.header')").click(function () {
top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
});
$('html,table').css('cursor','pointer');
</script>
Now it all works beautifully.
And I can sleep better tonight :)

Related

show hide field depend on select value sharepoint online

I have a list of 2 columns, the first one is "City" which is choice type.the second column is "Other" which is a single line of text.
when the user chooses "other " in City I want "OtherCity "column appears, if he chooses another choice, I want to hide.
I write the code using simple javascript, I do not want to use any library just simple code in javascript.
<script type="text/javascript">
function mySelectfunction(){
getValue = document.getElementById("City").value;
if(getValue == "other"){
document.getElementById("OtherCity").style.display ="none";
}else{
document.getElementById("OtherCity").style.display ="block";
}
}
</script>
but it does not work. can you help make it work?
*another question: if the second column which I want to hide type is "lookup " will the code be different?
My test code for your reference,and Choice and lookup column do not need to change the code.
Add a script editor in NewForm,and insert the code into it(replace the column name).
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
<script src="https://xxxx.sharepoint.com/sites/dev/SiteAssets/sputility.js">
</script>
<script>
$(document).ready(function () {
// Get a single select dropdown field
var relacionField = SPUtility.GetSPField('CityLookUp');
// create a function to show or hide Rates based on Rate value
var showOrHideField = function() {
var relacionFieldValue = relacionField.GetValue();
// Hide the Rates field if the selected value is Especial
if(relacionFieldValue === 'other') {
SPUtility.ShowSPField('Other')
}
else {
SPUtility.HideSPField('Other')
}
};
// run at startup (for edit form)
showOrHideField();
// make sure if the user changes the value we handle it
$(relacionField.Dropdown).on('change', showOrHideField);
});
</script>
You can download sputility.js here: https://archive.codeplex.com/?p=sputility
Updated:
Did the code above report any error?
JavaScript code:
ExecuteOrDelayUntilScriptLoaded(show,"sp.js");
function show () {
//Get the select element corresponding to column
var selectElement=document.getElementById('CityLookUp').parentNode.parentNode.childNodes[3].childNodes[3].childNodes[0];//chnage coulmn name
//get tr the hidden column located
var trElement=document.getElementById('Other').parentNode.parentNode;//change column name
//hide tr when we get into page,if the default value is 'other' ,do not need this
trElement.style.display='none';
//select change event
selectElement.onchange = function () {
var index = selectElement.selectedIndex;
//get option value
var value = selectElement.options[index].text;
if(value==='other'){
//show tr element
trElement.style.display='';
}else{
//hide tr element
trElement.style.display='none';
}
}
}
The code idea is to find the corresponding select element and decide whether to hide the tr element where column other is located according to the value of option.
Tip: Our page dom structure may be different, so you may need to modify the code according to your page dom structure. You could view your page dom structure by Developer tool.
Test result:

asp.net pass value from javascript to control on a modal popup

Ok, I changed the title because I can't get anywhere with previous approach, so I'm returning to the original question: how can I pass a variable obtained through javascript to a textbox on a modal popup?
I already tried to place a hidden field and even a textbox on the parent page, inside or outside an update panel, but when I click on the linkbutton that opens the modal popup their values are resetted to default.
I already searched and tried many different ways but I can't succeed.
I have a table in a repeater and I need to know the cells selected by the user: start and ending cell of the selection. I accomplish that with this javascript:
$(function () {
var mouse_down = false;
var row, col; // starting row and column
var $tr;
$("#tblPersonale td")
.mousedown(function () {
$("#col_to").html('?');
mouse_down = true;
// clear last selection for a fresh start
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
$tr = $(this).parent();
row = $tr.parent().find("tr").index($(this).parent());
col = $tr.find("td").index($(this));
$("#row").html(row);
$("#col_fr").html(col - 1);
return false; // prevent text selection
})
.mouseover(function () {
if (mouse_down) {
$("#col_to").html('?');
if ($tr[0] === $(this).parent()[0]) {
var col2 = $(this).parent().find("td").index($(this)); // current column
var col1 = col;
if (col > col2) { col1 = col2; col2 = col; }
$("#col_fr").html(col1-1);
$("#col_to").html(col2 - 1);
// clear all selection to avoid extra cells selected
$(".highlighted").removeClass("highlighted");
// then select cells from col to col2
for (var i = col1; i <= col2; i++) {
if (col1>1){
$tr[0].cells[i].className = "highlighted";}
}
}
}
})
.bind("selectstart", function () {
return false; // prevent text selction in IE
})
$(document)
.mouseup(function () {
mouse_down = false;
});
});
So, when user selects one or more cells I have the start/end value in here:
<span id="col_fr" runat="server" enableviewstate="true">?</span>
<span id="col_to" runat="server" enableviewstate="true">?</span>
Then, when user click a linkbutton I want to use these values to write a text in a textbox on the modal popup that shows. As I said, I can't make it work, anything I tried the result is that the values are lost when popup shows, even if I assign values to global variables before showing the popup.
This is my linkbutton:
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click">
The idea behind the old question was to pass the values to the url as parameters and then in the page load use them, but then the table selection doesn't work anymore because at every selection the page refresh because of the url change.
Please anyone, I'm totally lost and not for lack of trying!
OLD QUESTION
asp.net pass a control value as parameter in onclientclick
I found similar questions but no one answer to my problem (or at least, I can't make anything working).
I want to concatenate to the url of the active page some parameters like Home.aspx?col_fr=2 where instead of the fixed "2" I want to pass the value of a hidden field. How can I achive that?
This is my current code:
<asp:hiddenfield runat="server" id="hdnColonnaDa" EnableViewState="true" />
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="window.location='Home.aspx?col_fr=2';return false;">
Thanks
It just have to move the parameter code o a javascript function like
function getURL(){
var param1 = someField.value/*get field value*/;
var url= "Home.aspx?col_fr="+ param1;
window.location= url;
return false;
}
Html
<asp:LinkButton runat="server" ID="lnkAddDip" OnClick="lnkAddDip_Click" OnClientClick="getURL()">
Don't use UpdatePanel or Modal popup server side. You can use a Thickbox or similar jquery plugin to open the popoup.
Popup can be an inpage div or another page. In case of page, you can easily pass parameters in the url, in case of inpage div, you can get hidden field values.
You can find jquery overlay as Thickbox: just add css and js to your site, the right class on the link and fix the url to open.
Solution using another page
Imagine to use Colorbox (http://www.jacklmoore.com/colorbox/):
PRE
Suppose you have your variable values in some hidden field in your page
TODO
include jquery in your page
Download and include css and js for colorbox
In your page add a html tag with on click event
Add a script section in your page
function openLink()
{
var hiddenValue= $("#col_fr").text(); // or .html()
var urlToOpen = "yourpage.aspx?ids=" + hiddenValue;
$.colorbox({
iframe: true,
width: "75%",
height: "75%",
href: urlToOpen
});
}
Then in Yourpage.aspx you can use url parameter "ids".
Code is not tested!
Finally I did what I want by tuning the original javascript function.
I added 3 hiddenfield on the page and then I add this bit
var hdncol_fr = document.getElementById("hdncol_fr").value;
var hdncol_to = document.getElementById("hdncol_to").value;
var hdnrow = document.getElementById("hdnrow").value;
if (hdncol_fr = '?'){
document.getElementById("hdncol_fr").value = col - 1;
document.getElementById("hdncol_to").value = col2 - 1;
document.getElementById("hdnrow").value = row;
}
This way the hidden fields values are set only when user actively select some cells, when there is a postback event the javascript function returns '?' for the 3 values, so with the added code the hidden field maintains the previous values until user select something else.

Making editable table work cross-browser

I've been working on an ASP.NET page containing a ListView. When the user clicks a row, the content of the last (visible) column of this (once parsed) HTML table is replaced with a textbox (by means of jQuery), making the value editable.
So far, this works like a charm in Chrome but no joy in IE10.
In this jsfiddle, the value becomes editable but then the Save button doesn't work as expected.
In IE the textbox doesn't appear. Funny detail: if I comment out the four vars (invNr, newInvNr, oldHtml and spanWidth), the input element DOES appear in IE10 but of course I have no data to work with. Really REALLY weird.
The jQuery:
$(document).ready(function () {
$('tr[id*="itemRow"]').click(function () {
$clickedRow = $(this);
//this makes sure the input field isn't emptied when clicked again
if ($clickedRow.find('input[id$="editInvNr"]').length > 0) {
return;
}
var invNr = $clickedRow.find('span[id$="InvoiceNumber"]').text(),
newInvNr = '',
oldHtml = $clickedRow.find('span[id$="InvoiceNumber"]').html(),
spanWidth = $clickedRow.find('span[id$="InvoiceNumber"]').width();
$clickedRow.find('span[id$="InvoiceNumber"]').parent('td').html('<input type="text" ID="editInvNr"></input>');
$clickedRow.find('input[id="editInvNr"]').val(invNr).focus().on('input propertychange', function () {
$clickedRow.find('span[id$="SaveResultMsg"]').hide();
$clickedRow.find('td[id$="SaveOption"]').show();
$clickedRow.find('input[id*="btnSaveInvNrFormat"]').show();
newInvNr = $(this).val();
if (newInvNr == $clickedRow.find('span[id$="InvoiceNumber"]').text()) {
$clickedRow.find('td[id$="SaveOption"]').hide();
}
});
});
$('tr[id*="itemRow"]').focusout(function () {
$rowLosingFocus = $(this);
var previousValue = $rowLosingFocus.find('input[id$="editInvNr"]').val();
$rowLosingFocus.find('input[id$="editInvNr"]').closest('td').html('<asp:Label ID="lblInvoiceNumber" runat="server" />');
$rowLosingFocus.find('span[id$="InvoiceNumber"]').text(previousValue);
});
});
function UpdateInvoiceNrFormat(leButton) {
$buttonClicked = $(leButton);
$buttonClicked.focus();
var companyName = $buttonClicked.closest('tr').find('span[id$="lblCompanyName"]').text(),
invoiceType = $buttonClicked.closest('tr').find('span[id$="lblInvoiceType"]').text(),
invNrFormat = $buttonClicked.closest('tr').find('span[id$="lblInvoiceNumber"]').text();
PageMethods.UpdateInvoiceNumberFormat(companyName, invoiceType, invNrFormat, onSuccess, onError);
function onSuccess(result) {
$buttonClicked.hide();
$buttonClicked.siblings('span[id$="SaveResultMsg"]').text(result).show();
}
function onError(result) {
$buttonClicked.hide();
$buttonClicked.siblings('span[id$="SaveResultMsg"]').text('Error:' + result).show();
}
}
I've tried various combinations of jQuery statements, chaining and avoiding chaining, placing it at the bottom of the page as someone suggested, commenting out various parts of the code out of sheer desperation. Still nada.
There was no way to make the html() method replace the html correctly in IE10, although I never did find out exactly why. I ended up writing both elements into the table cell, set style="display:none" for one of them and use show() / hide() and that's good enough for me (and apparently for IE10 as well).
For anyone encountering the same issue: this is a workaround, not a solution in the strictest sense.

Creating Dynamic Javascript AJAX

Alright, I'm currently working to create on an account mainpage a applet to show each "kid" the user has registered to the site. My idea is simple :
Kid 1 / Kid 2 / Kid 3
As buttons (with style and such) when he goes on this page. When he clicks on one of those buttons/names, I use javascript to show the description of the infos of the kid, etc. When I click on another name, the current content closes and shows the new appropriate content.
The content is dynamically created, so the id's of the divs containing the info are named after the number of kids. Example : content_Info_Kid1, content_Info_Kid2, ... It doesnt matter how many kids there are, they will be named content_Info_Kid32 if need be.
Now, I'm not too comfy with AJAX and javascript in general. In fact, I am not at all.
My first idea was to do this in a separate javascript file.
$(document).ready(function() {
$("#content_info_kid1").hide();
$("#content_info_kid2").hide();
$("#content_info_kid3").hide();
$("#KID_1").click(function () {
if ($("#content_info_kid1").is(":hidden")){
$("#content_info_kid2").hide();
$("#content_info_kid3").hide();
$("#content_info_kid1").show("slow");
$(this).css("font-weight","bold");
$("#KID_2").css("font-weight","normal");
$("#KID_3").css("font-weight","normal");
}
});
$("#KID_2").click(function () {
if ($("#content_info_kid2").is(":hidden")){
$("#content_info_kid1").hide();
$("#content_info_kid3").hide();
$("#content_info_kid2").show("slow");
$(this).css("font-weight","bold");
$("#KID_1").css("font-weight","normal");
$("#KID_3").css("font-weight","normal");
}
});
$("#KID_3").click(function () {
if ($("#content_info_kid3").is(":hidden")){
$("#content_info_kid2").hide();
$("#content_info_kid1").hide();
$("#content_info_kid3").show("slow");
$(this).css("font-weight","bold");
$("#KID_1").css("font-weight","normal");
$("#KID_2").css("font-weight","normal");
}
});
});
Obviously, this is not dynamic. And I don't want to create 32 alternatives, of course. Can somebody point me the right direction to create a dynamic way to show my content based on the number of kids ?
EDIT (see bottom for updated on loading just one kid data at a time)
An example on how you could achieve that:
<style type='text/css' media='screen'>
button { margin-left:20px; display:inline; }
</style>
<script type='text/javascript' src='jquery-1.7.1.min.js'></script>
<script type='text/javascript'>
function loadKidData(kidID) {
switch (kidID) {
case 1 : $('#kName').text(' John Doe');
$('#kNickname').text(' Speedy');
$('#kHobbies').text(' Booling');
break;
case 2 : $('#kName').text(' Mathews Doe');
$('#kNickname').text(' Slowy');
$('#kHobbies').text(' Basketball, baseball');
break;
case 3 : $('#kName').text(' Jackson Doe');
$('#kNickname').text(' J-DOE');
$('#kHobbies').text(' Archery');
break;
case n : $('#kName').text(' Enne Doe');
$('#kNickname').text(' The-Nanny');
$('#kHobbies').text(' Anything goes');
break;
default : $('#kName').text('');
$('#kNickname').text('');
$('#kHobbies').text('');
}
}
jQuery( function () {
$('.nav').click( function () {
loadKidData($(this).html().replace('KID ','')*1.0); // *1.0 same as parseInt(...,10).
})
});
</script>
</head>
<body>
<button class='nav' >KID 1</button><button class='nav' >KID 2</button><button class='nav' >KID 3</button>
<div id='KID_INFO' style='margin:20px auto; overflow:auto; ' >
<p>Name:<span id='kName'></span></p>
<p>Nickname:<span id='kNickname'></span> </p>
<p>Hobbies:<span id='kHobbies'></span> </p>
</div>
</body>
Sample at: http://zequinha-bsb.int-domains.com/kidsinfo.html
Now, as far as dynamically displaying the data, it will have to do with your resources: database? If so, you could read the data and pass it over:
$.get('url-of-the-database-reading-script',function (data) {
// assumed all data comes back formatted:
$('#KIDS_INFO').html(data);
});
I can/could help you further, more details would help. Are you using classic asp (.asp); php; etc?
EDIT:
Instead of this:
jQuery( function () {
$('.nav').click( function () {
loadKidData($(this).html().replace('KID ','')*1.0); // *1.0 same as parseInt(...,10)
})
});
Do this:
jQuery( function () {
$('.nav').click( function () {
$.get('your-data-fetching-url?kidID='+$(this).html().replace('KID ','')*1.0, function (data) {
//assumed the data comes back formatted:
$('#KIDS_DATA').html(data);
})
})
});
Note that I put a question mark at the end of the url; followed by the querystring kidID=
Give each "Kid" button the same class and use that for the click handler. From there, you can associate the "content_info_kid" with the "kid" button either by
1)Using the index of the element. The button for kid2 should be index 1 relative to its parent and the content_info for kid2 should also be index 1 relative to its parent.
or
2)Extract the number from the ID of the button.
Both approaches are documented below.
$('.kid_button').click(function(){
// get number from index (this starts at '0')
// if your kid #'s start at 1, you should add 1 to this
var id = $(this).index();
// OR...get number from id where id format is kid_{#}
var id = $(this).attr('id').split('_').pop();
// now we have the number to append to everything else
// we should also associate all "content_info" with a class
// which we will call "kid_content"
if($("#content_info_kid"+id).is(":hidden")){
// hide all of the 'kid_contents'
$(".kid_content").hide();
// show the one we want
$("#content_info_kid"+id).show("slow");
// normalize all buttons
$(".kid_button").css("font-weight","normal");
// bold this one
$(this).css("font-weight","bold");
}
});

Dynamic paging using divs and Javascript

I have a recordset loop that creates a table, and every 9 items it wraps a div around them so basically looks like:
<div>
<table>rs1, rs2 ----> rs9</table>
</div>
<div>
<table>rs10, rs11 ----> rs18</table>
</div>
etc...
Now, I want it so at first only the first div is showing and the others are hidden, but I have ASP loop that generates clickable links for the various divs (pages) and clicking on any given link will show that div and hide all the others.
Here is the asp code I have so far:
Dim i
If totalPages > 1 Then
Response.Write("<div id='navigation'>")
For i=1 to totalPages
Response.Write ("<a href='' onlick=''>"& i &"</a> | ")
Next
Response.Write("</div>")
End If
Now I just need to figure out the javascript...
To make this easier, you should identify your tables somehow. Give them an ID that identifies a specific resultset and a classname that identiefies all resultsets:
<table id="resultset-1" class="resultset"> ...
Then you can bind an event to the links in your navigation element:
window.onload = function() {
document
.getElementById('navigation')
.getElementByTagName('a')
.onclick = function() {
var id = parseInt(this.innerHTML, 10);
document.getElementsByClassName('resultset').style.display = 'none';
document.getElementById('resultset-'+id).style.display = 'block';
return false;
}
}
I haven't tested this and my vanilla JS skills are a bit rusty, but it should work to my understanding. Just for the kicks, here's a version using jQuery which I can guarantee to work:
$(function() {
$('#navigation a').click(function() {
var id = parseInt($(this).html(), 10);
$('.resultset').hide();
$('#resultset-'+id).show();
return false;
});
});
Remember to initially hide all but the first div somehow – you don't need to use JS for that, you can use ASP to print style="display: none;" to all tables you want to hide, for example.

Categories

Resources