Same button for 2 tables selection jquery - javascript

i have a page and i got 2 tables in that page. I want to pass the value from rows to one .php page but with the same button. My code is this:
JS code:
var flag;
function highlight(e) {
if (selected[0]){
selected[0].className = '';
flag='1';
}
else if (selected2[0]){
selected2[0].className = '';
flag='0';
}
e.target.parentNode.className = 'selected';
alert(flag);
}
var table = document.getElementById('data-table'),
selected = table.getElementsByClassName('selected');
var table2 = document.getElementById('data-table-aux'),
selected2 = table2.getElementsByClassName('selected');
table.onclick = highlight;
table2.onclick=highlight;
$("#tst").click(function(){
if(flag=='1'){
var value =$(".selected td:first").html();
value = value || "Nenhuma coluna selecionada";
window.open("info_detalhada.php? data2="+value,'_blank','toolbar=0,location=no,menubar=0,height=550,width=650,lef t=200, top=300'); }
else if(flag=='0'){
var value =$(".selected td:first").html();
value = value || "Nenhuma coluna selecionada";
window.open("info_detalhada2.php? data2="+value,'_blank','toolbar=0,location=no,menubar=0,height=550,width=650,lef t=200, top=300');
}
});
HTML CODE
creating 2 tables
<table style="float: left" id="data-table"></table>
<table style="float: left" id="data-table-aux"></table>
(Dynamic tables )
button:
<input type="button" id="tst" value="Detailed information" />
The problem is that first time i select a row the variable flag will have the old value and not the new value from click.
For example, first time i click a row flag = undefined , second time got the value of the table selected (0 or 1) , if i click on other row the flag wont change and will got the old value (or 0 or 1).
Any tips ?
Thanks
edited: i didnt put the html in first place because i dont think it's an html solution, I dont have a fiddle created because i'm using dynamic table's but i will try to make a fiddle with my example and i will put here when it's done ;)
Fiddle : https://jsfiddle.net/gwg639Lf/9/

Let me suggest a more generic approach
First of all wrap your tables in a div
<div class="data-tables">
<table style="float: left" id="data-table"></table>
<table style="float: left" id="data-table-aux"></table>
</div>
Then delegate the click event handlers
$('.data-tables').delegate('table', 'click', function(event) {
$this = $(this)
$this.addClass('active').removeClass('inactive')
$this.siblings().addClass('inactive').removeClass('active')
});
This function does the following:
Add class active and remove inactive (if exists) to the selected item/table
Remove the class active and add class inactive from all adjacent tables
In this way you will only have one active table at the time
Then declare your button handler
$("#tst").click(function(){
var value = $('.active').html()
// Use the value as you want
})
This code will work no matter how many tables you add to the div

You're setting the class name of the element after the condition statement. Hence, the first time, your flag variable is undefined.
Try putting it in the beginning of the highlight function.
function highlight(e) {
e.target.parentNode.className = 'selected';
if (selected[0]){
selected[0].className = '';
flag='1';
}
else if (selected2[0]){
selected2[0].className = '';
flag='0';
}
alert(flag);
}
JsFiddle: https://jsfiddle.net/gwg639Lf/10/
Edit:
Add it before and after the condition. Adding it before the condition gives you the class name to initialize the flag variable. Adding it after gives the formatting bar.
JsFiddle: https://jsfiddle.net/gwg639Lf/13/

Ok, after some tests on Kostas Pelelis functions, i found a solution that is valid for my problem.
here is the code of JS:
var flag;
$("#data-table tr").click(function(){
$("#data-table-aux tr").addClass('selected').siblings().removeClass('selected');
$(this).addClass('selected').siblings().removeClass('selected');
flag='1';
});
$("#data-table-aux tr").click(function(){
$("#data-table tr").addClass('selected').siblings().removeClass('selected');
$(this).addClass('selected').siblings().removeClass('selected');
flag='0';
});
$('#tst').on('click', function(e){
if (flag=='1')
alert($("#data-table tr.selected td:first").html());
else if (flag=='0')
alert($("#data-table-aux tr.selected td:first").html());
});
Here is the fiddle --> fiddle
Thank you all for the help ;)

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.

How to get second column value of invoked row in table?

In below context menu example .. how to get value of second column that invoked it?
Refer Link
tried with $(this).find('td:second').text() but it didnt work. :P
How to do this?
No need to write such this long code here. Just assign a class name to each <tr> like row then add click event listener like this:
$(".row").click(function () {
var txt = $(this).children().eq(1).text();
alert(txt);
});
jsfiddle
You can get your row or invoked row then use cells proberty to access second column
$(".row").click(function () {
var colText = $(this).cells[1].textContent;
// or-> var colText = row.cells[1].textContent;
});

Change selected tr color back after selecting new tr

Thus far I've figured out most of the code I need to select a radio button inside of a <tr> when the row is clicked & to change the color of the <tr> when it's clicked, but I need to be able to change the color back & change the color of a new <tr> if the user selects a different one. Right now it just keeps changing the color of the rows, but doesn't change them back. Code is below:
<script>
var prevTr;
$('tr').click(
function() {
$('input[type=radio]',this).attr('checked','checked');
$(this).addClass('selectedtr');//css('background-color', 'Green');
prevTr = $(this).id;
$("#"+prevTr).removeClass('selectedtr');
}
);
...
Remove the selectedtr class from all tr elements first, then add it to the current one:
$('tr').click(
function() {
$('input[type=radio]',this).prop('checked','checked');
$(this).siblings().removeClass('selectedtr');
$(this).addClass('selectedtr');
}
);
Edit - I don't think David Thomas's answer is quite what you're looking for, but I do think the siblings() select would be more efficient than selecting all tr elements.
Another Edit
In reference to your comment: prop should be used instead of attr. Here's a fiddle:
http://jsfiddle.net/xQyAV/
I would use css:
binput[type=radio]:hover {
//here edits
//the setting back happens automaticly
}
I'd suggest:
$('input[type=radio]').change(function (){
var self = this,
row = $(self).closest('tr');
row.addClass('trSelected').siblings().removeClass('reselected');
});
I think it only needs to remove the class before remembering the current identifier:
$(function () {
var prevTr = false;
$('tr').click(function () {
if (prevTr) {
$("#" + prevTr).removeClass('selectedtr');
}
prevTr = $(this).id;
$('input[type=radio]', this).attr('checked', 'checked');
$(this).addClass('selectedtr');
});
});

How to target another element on the same row in a table with jQuery

I am trying to use jQuery to pick an item in a table row that will make a change within the same row
<table>
<tr id="t1"><td><input type="checkbox" id="t1" value="" /></td></tr>
<tr id="t2"><td><input type="checkbox" id="t2" value="" /></td>{want new stuff here}</tr>
</table>
In this instance - if I select the checkbox with the id of 2 - I would want a new column to be added/appended just after the last and if this same checkbox was unchecked it would remove the content just added.
Can anyone suggest how this is done?
Make sure your id values are unique on all elements, then you can use .parents("tr"):
$(".mytable tr :checkbox").click(function () {
var checked = $(this).is(":checked"),
$tr = $(this).parents("tr").first();
if (checked) {
$tr.append("<td></td>");
} else {
$tr.find("td:last").remove();
}
});
If you're adding multiple <td>'s, then store a reference to them or use an identifier to find them again. I'm assuming you just want to add/remove a column at the end.
As with anything jQuery, there are multiple solutions! This was the one off the top of my head.
I would better have dynamic content inserted into specified TD cell instead of creating and removing td container so that you would not have to take care about correct colspans.
$('#table :checkbox').change(function() {
var cont = $(this).closest('tr').find('.content');
if ($(this).is(':checked')) {
cont.append('Some content');
}
else {
cont.empty();
}
});
Check this out:
http://jsfiddle.net/sCjXg/1/
See this jsFiddle for a quick-written example
$(function(){
$("#t2").find("input").click(function(){
if($(this).is(":checked")){
$(this).parents('tr').append("<td class='t2-add'>have new stuff</td>")
}
else{
$(this).parents('tr').find('.t2-add').remove()
}
})
})
Try something like the following:
$('[type="checkbox"]').change(function () {
var $this = $(this);
if ($this.is(':checked') {
$this.closest('tr').append('<td></td>');
} else {
$this.closest('tr').children('td:last-child').remove();
}
});
This uses the jQuery .closest(selector) method.

Categories

Resources