I read a lot of things on stackoverflow, but nothing help me :(
I have this HTML table, loaded by ajax request :
<table class="table table-striped table-hover choix_annonce_table">
<thead>
<tr>
<th>Sélection</th>
<th>Visuel</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" value="45" name="idAnnonce"></td>
<td><img alt="Annonce 1" src=""></td>
</tr>
<tr>
<td><input type="radio" value="46" name="idAnnonce"></td>
<td><img alt="Annonce 2" src=""></td>
</tr>
</tbody>
</table>
I try to detect when radiobutton is checked, but no of the following issues work (in js file included on my "main" page):
$(document).ready(function() {
$("input[name=idAnnonce]").click(function(){
alert("xx");
});
});
OR
$(document).ready(function() {
$("input[name=idAnnonce]:radio").change(function () {
alert("xx");
});
});
Do you have in idea?
EDIT : when I load JS directly into my loaded table with ajax, it works.
Why ?
This happens because the .click() and .change() methods, along with all other event handlers, only watch for these events on elements that are present at the time the events are attached.
To solve this, instead of using this:
$('input[name=idAnnonce]').change(function() {
// ...
});
Use something like this instead:
/* Use 'body' or any element that will contain the form */
$('body').on('change', 'input[name=idAnnonce]', function() {
// ...
});
This will watch for click events passing up to the body, and only call the function for those that match the selector.
If your javascript is loaded directly into the html file, then it's being executed in line as the html file is loaded and parsed. When the javascript is in a separate file, it needs to be invoked. You could do this by executing an "onload" function as part of your body tag statement. That part of your html is missing, so it's unclear whether you're actually loading anything when your table is loaded. You can also execute these event monitors through a callback at the end of the ajax load.
When loading the table via ajax, you will need to bring in the javascript through the ajax call. Meaning the table that comes in should also contain the javascript that references the table. The DOM on the parent page doesn't know about the table, so the javascript on the parent page won't act on new content.
$(document).ready(function() {
$('input[type=radio][name=idAnnounce]').change(function(evt) {
console.log(evt.target.value)
});
});
The selector you were using was wrong.
The above code should help
cheers
Related
I have a HTML-code like this here:
<div id="overview" class="fadeable">
<table id="exportTable">
<tr>
<td style="width: 500px;"><strong>Col 1</strong></td>
<td style="width: 15px;" class="aligned_td"><strong>Col 2</strong></td>
</tr>
<% call getLocationPercentages(is_nll) %>
</table>
</div>
As you can see, I'm calling an asp-function after the first tr. The output it generates is correct (after reloading the site. However, I don't want to reload it.
For this scenario, I made a small JS-function, which works in Chrome, but not in IE (7).
Just a quick note: I can't just not support IE 7.
$(document).on("click", "#updateLocation", function() {
$.ajax({
url: "my-file.asp",
type: "GET",
scriptCharset: "utf-8",
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data
});
$('#exportTable').load(location.href + " #exportTable");
}
I read the documentation for load and as I said, it works in chrome. IE however just "hides" the output. After submitting (or pressing this button (which is in another div, if that is important)) the table just vanishes, but the dom is correct. There is no CSS rule or what so ever what could hide that table. It would affect the other browsers as well though.
The DOM after submitting also has the correct values (so it is "reloaded", but not displayed)
Ideas? Familiar with that problem?
Update
I figured out, that the Table isn't generated properly. My HTML results in something like this:
<table id="exportTable">
<table id="exportTable">
correct content here
</table>
</table>
When I move the inner table over the other, so it is alone again, the display is correct. For some reason, instead of re-generating the content, it adds another table.
I tried to "unwrap" the 2nd occurence with this, but that didn't do the trick:
var e = $('#exportTable:last');
e.prev().insertAfter(e);
The inner table isn't selected with that, it affects only the outer one
e.unwrap()
didn't do it either
I can't even reach it with each in a loop. It is simply left behind.
I don't know why, but "reloading" a table ends up in having 2 tables with the same classes + id's, where the 1st one is just a wrapper of the 2nd one.
I wrapped a <div> around the table, changed my JS to reload that div and now it is working.
HTML
<div id="tableWrap">
<table id="exportTable" class="exportTable">
<tr>
<td style="width: 500px;"><strong>col 1</strong></td>
<td style="width: 15px;" class="aligned_td"><strong>col 2</strong></td>
</tr>
<% call getLocationPercentages(is_nll) %>
</table>
</div>
JS
$('#tableWrap').load(location.href + " #exportTable");
I am not sure if your way of doing that is correct or what do you really want to achieve.
First of all - when you create HTML table you should create it like:
<table>
<thead>
<tr>
<!-- columns descriptions here -->
</tr>
</thead>
<tbody id="ContentId">
</tbody>
</table>
And only update tbody element.
Secondly, at first start of application you should render data with ASP.NET, but then (if you want to use AJAX with jQuery) the simplest (but not the best) way of updating that data would be:
JS
$("#UpdateTBody").on("click", function () {
$.ajax({
url : "script.asp",
...,
success: redrawTBody
});
// let's say success callback receives HTML in data argument
function redrawTBody (data) {
// disclaimer : this is simple, but not the best way
// drawing table
$("ContentId").html(data);
}
});
HTML returned by script.asp
<tr> <!-- row 1 --> </tr>
<!-- following rows -->
And when it comes to changing URL better way would be to use location.assign( location.href + '#ContentId' ) or location.hash="ContentId"
I have one javascript function named 'change2()' which is define in .ascx page's script tag.
I want to call that function from onclick event of img tag (Note : img tag is also on the same page).
It is compulsory to use img tag only for image.
I tried all the below ways, but unfortunately It doesn't work for me.
Test.ascx
<script language="javascript" type="text/javascript">
function change2() {
alert("Hi");
}
</script>
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclick="change2();" alt="Slider" />
</td>
</tr>
</table>
Second Way :
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" alt="Slider" />
</td>
</tr>
</table>
Please give me your suggestions to call javascript function from same page.
As I can see, the img id is imgLkU, so, instead of including the call in the img tag itself, you can subscribe the event "from the outside", i.e. do it like using $.on, (or $.click) like this:
$.on('click','#imgLkU', function() { change2(); });
// or equivalent $.on('click','#imgLkU', change2);
or
$.('#imgLkU').click(function() { change2(); });
// or equivalent $.('#imgLkU').click(change2);
Do it right after defining change2 in the same script tag.
I'd also recommend you doing the change2 definition and the event subscription inside an inmediately invoked function expression to avoid polluting the global javascript namespace.
(function() {
// define and subscribe here
})();
Because your elements all have runat="server", their onclick property is reserved for a backend-code actionlistener which will be executed at postback.
the onClientClick property is reserved to allow you to still attach javascript "listeners" to what is considered the client-side onclick.
keep in mind that returning false from an onClientClick handler will prevent postback from happening if an onclick listener is also hooked up. (onClientclick is executed before initiating the postback)
try this :
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclientclick="change2();" alt="Slider" />
The following function can be directly called from document.ready function like
$(function () {
$('#imgLkU').click(function () {
//do what ever you want
})
});
First, take out the runat="server" on your image since you are already using server tags to set the url. If you still want to use runat="server", you can either:
1: change your img into an <asp:Image> tag and use ImageSource instead of src and OnClientClick instead of onclick.
2: set the src attribute in the code behind.
After that, any click method - from your question to all the answers - should work.
If that still does not show the alert, then start taking out code until it does and work your way from there...
I have a specific rows in a HTML table that I do not want to be displayed when the page loads.
There will be an Ajax request made after the page loads that returns values that would populate the table rows.
So I would want to display these rows only after the Ajax returns with a response and until then I want to display a 'loading' message in place of these rows.
I tried adding these rows in a div and used jquery's show()/hide() appropriately but that didn't work.
I'm new to JS and jQuery, so any help is appreciated.
<html>
<body onload="my_ajax_func()">
<table>
.
. <!-- Other rows that will be displayed-->
.
<tr>
<th colspan=2 class="custHeader">High Value Flags</th>
</tr>
<tr>
<td align=right><div id="loading_msg"><b>Loading..</b></div></td>
</tr>
<tr>
<td id="val_header" class=caption>Value Tier: </td><td id="val"> </td>
</tr>
<tr>
<td id="hypo_val_header" class=caption>Hypo Value Tier: </td><td id="hypo_val"> </td>
</tr>
<tr>
<td id="service_type_header" class=caption>Service Type: </td><td id="service_type"></td>
</tr>
</table>
</body>
<script>
function my_ajax_func() {
//retrieves values for table rows
//on success calls another func, say display_data
}
function display_data() {
$("loading_msg").hide();
document.getElementById("val").innerHTML = <some_value>;
document.getElementById("hypo_val").innerHTML = <some_value>;
document.getElementById("service_type").innerHTML = <some_value>;
}
</script>
</html>
Basically, I want a div for 'loading' message which would be displayed by default. Once Ajax request completes successfully, that div must be hidden and another div (with these 2 table rows) must be displayed in it's place.
To hide your rows at page loading, just create two css classes like this:
.displayNone{
display:none;
}
.displayBlock{
display:block;
}
and use this class in your rows
<tr class="displayNone"></tr>
So when page loads, this rows will be hidden.
So, in ajax success put this js:
$(".displayNone").removeClass("displayNone").addClass("displayHidden");
Then, download some loading gif image like this:
http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif
After that, wrap this img tag in a div with "displayNone" class too, and use inverse way of your rows:
Before your ajax call, remove "displayNone" class from it, and put "displayBlock".
Finally, in ajax success, remove "displayBlock" class from div, and put back "displayNone" to hide it again.
Hope it help.
Some doubts, please let me know.
Regards
You Can use .done() method
$.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "ajax request completed" );
})
If you only need to change text values in the rows, you might be able to get away with a class value of "display: none" in CSS for each complete row, until you are ready to update it. But you are going to have to have some unique ID for each, or way of counting children, in order to find that row again when you need to update it. Also, your table needs to be valid without those rows.
The other way to handle this would be to just add new rows dynamically. If you do this, remember the rows do not exist in DOM until you insert them there, and so you can't reference them before.
as mentioned above ajax has some methods like before and done where you have opportunity to show and hide your elements.
<table>
<thead>
<tr><th>header 1</th><th>header2</th><th>header3</th><tr>
<tr id="loadingrow"><th colspan=3>Loading Data...</th><tr>
</thead>
<tbody>....
$.ajax({
url: "http://fdafdas",
beforeSend: function( ) {
$('#loadingrow').show();
}
})
.done(function( data ) {
$('#loadingrow').hide();
//load your data
}
});
As I heard, I should avoid using inline javascript handler on html. e.g. onclick = "FUNCTION_NAME".
If I have a table that is generated dynamically, Each row has a button for its own.
If I don't use incline Javascript function, how can I pass some parameters from the table to the event handler?
Maybe passing the data from the table cell is not very hard. What if some data is not shown on the table cell (for security reason), for example, a secret ID number that is used internally within the application and is not supposed to exposure on the html (Setting it in the invisible cell in the table is not safe because people who knows html can still inspect it). How can we pass those data that is not shown on the table from dynamic table to event handler in this case?
If we use inline click attribute, i.e. onclick="javascript_function(parameter_1, parameter_2)" on each row, that's fairly easy to pass any data I want, and I do not need to show those kinds of secure data on the html in order to pass it.
If you use jQuery, I would recommand
<table class="with-val">
<td data-val="17">17 points</td>
</table>
and
$('.with-val').on('click', 'td', function() {
var val = $(this).data('val');
console.log(val) //17
});
This way (with the on(eventType, selector, handler) signature), you don't have to reset the events if rows are deleted or added,
and the markup is much lighter (and it is considred best practice, as you add only one event handler for the whole table).
Giving markup
<td class="val" data-val="17">17 points</td>
you can get value from binding like this:
$('.val').on('click', function() {
var val = $(this).data('val');
console.log(val) //17
});
For this:
Setting it in the invisible cell in the table is not safe because
people who knows html can still inspect it
You must not send secure data in any way to frontend. User can stop your code with breakpoints, debug or anything else, and get this data even when it is not visible in html. In addition this data will be visible in responses for the requests that browser send
You can use click event to call a function, that does the task of getting the value of any paramater you wish.
Hope this helps.
<td><button id="btn">Click me</button></td>
<td><input type="hidden" id="secret_id"></td>
$("#btn").click(function(){
var id = $("#secret_id").val();
alert(id);
});
This is a possible solution:
HTML:
<table border="1">
<thead>
<tr>
<th>HEAD1</th>
<th>HEAD2</th>
<th>HEAD3</th>
</tr>
</thead>
<tr>
<td class="hiddenField">row1 col1</td>
<td>row1 col2</td>
<td><button class="seeHidden">btn1</button></td>
</tr>
<tr>
<td class="hiddenField">row2 col1</td>
<td>row2 col2</td>
<td><button class="seeHidden">btn2</button></td>
</tr>
</table>
CSS:
th:nth-child(1), td:nth-child(1){
display: none;
}
jQuery:
$(".seeHidden").click(function(){
var hiddenField = $(this).parent()
.siblings("td.hiddenField")
.html();
alert(hiddenField);
});
Check this link jsfiddle to see a working example.
Hope it's useful!
My question is! I am copying content from one table to another table and when I am doing this I need the function name to change to talentselect instead of driverselect which is attached to each table row. I still need to keep the variable values to parse. Just wondering if anyone can help me with this. I know that I should be binding the events to the elements with Jquery and not using OnClick but for now I need a solution to achieve this with the OnClicks.
Many Thanks!
The copying of the table
<table id="driverselectiontable" cellspacing="0">
<tr class="chosen" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="odd" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="even" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="chosen" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="even" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
</table>
<table id="talentselectiontable" cellspacing="0">
</table>
$("#talentselectiontable").html($("#driverselectiontable .chosen").clone(true).attr("class","odd"));
So basically I am copying all of the table rows that have the class named "chosen" but upon doing so I need to change the function call name to "talentselect". But each row in the table has different parameters being parsed which is allocated with PHP.
I have tried this piece of code but it is not working still
$("#talentselectiontable tr").attr("onclick").replace("driverselect", "talentselect");
I can't see the actual HTML of your table, so this may be slightly incorrect, but should get you started.
$("#talentselectiontable tr").attr("onclick", "return talentselect(this, value, value);");
This whole problem would actually be a lot easier if you used event handlers rather than inline onclick attributes. You could then use the jQuery live() function (see http://api.jquery.com/live/) that would mean that JQuery would take care of changing the function for you. Your solution would look something like this:
$("#driverselectiontable tr").live('click', driverselect);
$("#talentselectiontable tr").live('click', talentselect);
And then whatever code to ensure that your cloning code gets called.
Edit: In response to the comment, it looks like this is what you're after:
var clickval = $("#talentselectiontable tr").attr("onclick");
$("#talentselectiontable tr").attr("onclick", clickval.replace('driverselect', 'talentselect'));
That should get you going.
With a view to better JavaScript practice however, I would recommend another approach entirely. Rather than storing your parameter values in the 'onclick' attribute, store them in a data attribute. So your HTML would look something like this:
<table id="driverselectiontable" cellspacing="0">
<tr class="chosen" data-myparam1="value" data-myparam2="value"><td>driver</td></tr>
And so on. You can then use JQuery to parse the values:
function driverselect() {
var row = $(this),
param1 = row.attr('data-myparam1'),
param2 = row.attr('data-myparam2');
// rest of the code goes here
}
Your markup will be cleaner, and you can use the live() jQuery functionality as described above.