how do i do that ?
my html structure looks like this
EDIT: i have updated to html so it fits the rules.
<td id="1" class="LinkWrap">link</td>
i use this code:
$(".link").click(function() {
$(this).parent();
//some ajax code
});
To select the td by the id LinkWrap, but i need the value of the class,
the class' value is fetched by php && mysql and is the id of the element thats i fetched. therefor the value is not a constant i and i cant just say chose class with value 1 it could be 2 or 5932.
i need that value to my ajax script so i can insert when the user clicks that link.
if theres a better method please let me know :)
Aside from the fact that it's not recommended to start class names with a number. Use attr to get the class attribute.
$(".link").click(function() {
alert( $(this).parent().attr('class') );
});
Edit: You're better of using the data attribute as stated by others as well.
HTML
<td data-rowid="1" class="LinkWrap">link</td>
Javascript
$(".link").click(function() {
alert( $(this).parent().data('rowid') );
});
It sounds like you're doing data storage in the class attribute. Classes cannot start with a digit, and this means your invalid usage may wind up causing glitches in some browsers. You'd be better off using jQuery's data() in conjunction with data-* attributes instead.
Interstellar_Coder and wilbbe01 are both right in the execution but there is one thing in your code that is going to bite you. The td has an ID that, if repeated, could cause you referencing issues. id attributes should be unique across a DOM instance at peril of very unpredictable results across different browsers.
aside from that ceejayoz solution is best.
Since, as I mentioned in my comment, it seems you mixed up the classes and IDs, and to avoid the problem noted by ceeyajoz, I'd suggest using another approach:
$('.link').click(function(e){
var the_id = $(this).closest('td').attr('id'); //or parent().
$.ajax({
url: 'http://www.mysite.com/index.php?page_id='+the_id,
success:function(response){
alert(response);
}
});
e.preventDefault();
});
And in your html:
<td class="LinkWrap" id="td_1">link</td>
And in your php:
$id = $_GET['page_id'];
$id = str_replace('td_','',$id);
echo $id;
I think what you will need is the following.
$(this).parent().attr('class');
Edit: Ditto the data attribute stated by others as well.
Related
so, I have read just about every question on this subject, but the solutions don't work for my project, it seems that when I change the dropdown, it does the first event, but when I change to a different element it doesn't do anything else, but when I do this with an alert message it changes every time.
here is what I have to demonstrate what I mean
I tried .post it works great until I add php and all the dynamic functions, is it because I used $('#updateDiv').html(url);
I also hide and showed the div based on the change of the dropdown, but all that did was hid and show the div, I want the div to show the content based on a list of categories.
the PHP side will be dynamic, but if I do .html() none of the php renders properly.
http://fiddle.jshell.net/LrxUS/
$.post(url, function(data) {
$("#updateDiv").html(data);
});
As per the fiddle, you have specified
var mydropdown = $('#mydropdown');
but in the change function, you have specified $(mydropdown), either define only id in the variable or the object. Like,
var mydropdown = '#mydropdown';
$(mydropdown).change(function() {}
After that use $.ajax to get the dynamic content.
Ok, lets make it the simplest so that there is no room for mistake in the client side script. Use $.load method defined here.
AS:
$("#updateDiv").load(url);
And don't forget to check what your firebug, chrome inspector or fiddler says about your request in case if you don't get the required result.
I am displaying a table using php on an html page. I want to edit the cell contents (basically make changes to a value, and make ajax call to update the database). The requirement for me is to use an onblur function (I can get around with using onkeypress as well). Can anyone please tell me what would be the simplest way of getting the new value entered with the cell id?
The alert for x tells me its "object HTMLTableCellElement"
Thanks!!!
foreach($_RESPONSE['VENDOR_LIST'] as $r){
echo "<tr><td>".$r['fdEmail']."</td><td id='companyname_".$r['fdId']."' contenteditable='true' onblur='updateValue(id)';>".$r['fdCompanyName']." ".$r['fdId']."</td></tr>";
}
Javascript method
function updateValue(thisdata){
alert(""+thisdata);
var x=document.getElementById(""+thisdata);
if(x){
alert(x);
//var r = x.value;
}
else
alert("not found");
}
In your HTML, change updateValue(id) to updateValue(this.id);
Then put this inside your first if statement in the updateValue function.
if(x.innerText){
alert(x.innerText);
} else {
// Firefox support
alert(x.textContent);
}
The "value" of a table cell is not actually considered a value by javascript, it's just HTML. Try alerting x.innerText. See this question for obtaining cell contents by ID.
Also, I know everyone hates hearing this, but this would be much easier with jQuery.
In your code
var x=document.getElementById(""+thisdata);
Here x is an object, you need to write the required function to change the values or to get the values.
alert(x.innerHTML);
will give you the value of the cell.
Id mentioned in HTML td tag and the id in your getElementById deos not match.
(Use error console in your browser to get the javascript errors)
You may have to change your function like this
function updateValue(thisdata){
var x=document.getElementById("companyname_"+thisdata);
if(x){
alert(x.innerHTML);
}
else
alert("not found");
}
Your HTML code to :
foreach($_RESPONSE['VENDOR_LIST'] as $r){
echo "<tr><td>".$r['fdEmail']."</td>
<td id='companyname_".$r['fdId']."' contenteditable='true' onblur="updateValue('companyname_".$r['fdId']."');">".$r['fdCompanyName']." ".$r['fdId']."</td></tr>";
}
NOTE : I have not tested the code please make changes accordingly, Post here if you find it difficult :)
ALWAYS USE jQuery, It makes your task simple :)
This is my first attempt at jQuery and I'm using a basic tutorial I found here: http://papermashup.com/simple-jquery-showhide-div/#
This is my current code and how the jQuery works: http://jsfiddle.net/mZQsu/
As you can see, when you click the '+/-' it opens all 4 of the tables/DIVs.
How can I modify this code to open just the relevant secondary table/div according to the original table?
(Please note the secondary tables are generated dynamically from PHP and SQL data)
Thanks.
P.S all my code is here http://jsfiddle.net/mZQsu/ instead of clogging up this question page :)
DEMO fiddle
$('.toggler').click(function() { // had to differentiate the main togglers with a new class
var ind = $(this).parents('tr').index()-1; // could change
$(".slidingDiv").eq(ind).slideToggle();
});
$('.show_hide').click(function() { // this are the 'togglers' inside the big menus
$(this).parents(".slidingDiv").slideToggle();
});
The best solution would be if you tag each of your div's with an id. E.g.
<div class="slidingDiv" id="ip_127_0_0_1">
and then modify the equivalent links to do
$("#ip_127_0_0_1").slideToggle();
so just the associated div gets expanded.
See my updated fiddle: http://jsfiddle.net/mZQsu/1/
You can use the index of the row, and toggle only the matching row of the other table using jQuery index and eq
See the relivant docs here:
jQuery index
jQuery eq
This should work:
$('.show_hide').click(function() {
$(this).parents(".slidingDiv").slideToggle();
});
Since the slidingDiv class is a direct parent of the show_hide link, I could have used "parent" rather than "parents". The latter provides more flexibility because it traverses all ancestors looking for the class.
Here is a modified code - http://jsfiddle.net/mZQsu/3/
I have added show-hide1, show-hide2, show-hide3, show-hide4.
And clicking on it opens respectively slidingDiv1, slidingDiv2, slidingDiv3, slidingDiv4.
When you are binding to an event: You can always grab that event target and reference it.
$('.show_hide').click(function(e) {
$(e.target).parent("div.slidingDiv").slideToggle();
});
.parent() is a good place to start, but .closest() also might work. That being said, this is the preferred way to go about it.
On a side note if you ever want to do the opposite you could use .not(e.target) and all the other elements except for the one your click will be called.
Since your html is PHP-generated, it should not be a problem to include unique IDs for both +- links and sliding divs, for example:
a href="#" class="show_hide" id="show_hide2"
And
div class="slidingDiv" id="slidingDiv2"
Then in your click function you get the index of the div that you want to open:
$(.show_hide).click(function(){
var $str = $(this).attr('id');
var $index = $str.charAt( $str.length-1 );
});
Now you can use index to open the div:
var divName = "#slidingDiv" + $index;
$(divName).slideToggle();
Hi all got a small problem accessing a looped php variable. My script loops through and uses x and y from a mysql database. It also loops the id out which I cannot get access to, it comes up as undefined. I am using a mouse out function to detect each separate div that has been looped and get specific id.
Help very much appreciated!
Javascript to get attributes ready for database manipulation:
$(this).mouseout(function() {
var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.
});
Looped PHP to get attr form:
$get_textsticky_result=mysql_query($get_textsticky_query);
while($row=mysql_fetch_assoc($get_textsticky_result)){
$x = $row['textsticky_x'];
$y = $row['textsticky_y'];
echo '<div class="textsticky" style="position: absolute; left:'.$x.'px; top:'.$y.'px;" textstickyid="'.$row['textsticky_id'].'">
<div class="textstickyvalueholder"contentEditable="true">'. $row['textsticky_text'] .'
</div><button>Like</button></div>';
}
?>
Can get other looped vars e.g. $row['textsticky_text']; and x and y for position without issue, Is there a better way to do this? I have a feeling the inline style is affecting it but not sure....
Okay, I am just going to go out on a limb here and assume your initial selector is incorrect. $(this) is the window in typical code flow.
$(this).mouseout(function() {
var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.
});
Should be:
$('div.textsticky').mouseout(function() {
var stickytext_id = $(this).attr('textstickyid');//alerted out returns undefined.
});
Also, as Kris mentioned in comments, instead of inventing tags use the data attribute which is a part of html5.
<div class="textsticky" data-textstickyid="blah" />
It can then be accessed via jQuery's data method.
http://jsfiddle.net/kQeaf/
And as long as we are offering advice, if you are in jQuery 1.7+ you should be using prop instead of attr for accessing properties (unless of course you decide to use the data method) just recommended.
Your selector on the mouseout event may be wrong: (depending on the context)
$(".textsticky").mouseout(function() {
var stickytext_id = $(this).attr('textstickyid');
});
EDIT:
OK, I believe I've found a way around the issue using the info posted by #ManseUK along with #Johan's comment. As a n00b I can't answer my own question but I've added an explanation below the question in case it helps anyone else out.
I am re-writing part of an e-commerce solution which was written by
another development team some years ago. In the new version, we are
experimenting with shortening the user journey using Ajax but doing so
gives JavaScript errors and causes some functions to fail. Dev URL is
here:
http://cognition.thelightbulb.co.uk/type-18/general-purpose-lamps-and-bulbs/craftlight-daylight
The errors appear once the dropdowns have been selected and the
product displays.
The errors are displaying most notably in IE7:
Error: 'frm.qty' is null or not an object
Error: 'qty.value' is null or not an object
I believe this is where the problem is coming from:
var frm = document.frmOrder;
var qty = frm.qty;
In the lines above, frmOrder is the name of the form and qty is
the name of the input for product quantity.
Compare that to http://cognition.thelightbulb.co.uk/product-54 where
the product loads without the Ajax selection process and you'll see
that the functions work correctly.
I suspect that the problem is to do with the fact that var frm =
document.frmOrder; is not working due to the way it relates to the
DOM when loaded with Ajax.
I am using innerHTML=xmlhttp.responseText as the Ajax method. Is
there an alternative way to define var frm so that it will function
properly when loaded with Ajax?
EDIT:
Using the info posted by #ManseUK along with #Johan's comment, I added another argument to CheckMinQty(minorder) so that it now looks like this...
function CheckMinQty(minorder,qty)
...where qty is passed to the function on an onclick event as document.forms['frmOrder'].qty.value
I then moved the whole function out into a separate .js file. It's maybe not the best approach but it still feels tidier for the Ajax call to just return workable HTML which CheckMinQty can use rather than bringing in a whole load of <script> and then trying to run it.
Thanks for all the suggestions and I'd welcome any comments about the approach/solution outlined above.
Change this
var frm = document.frmOrder;
to this
var frm = document.forms['frmOrder'];
That will give you a handle to the form
document.frmOrder refers to the element with id frmOrder on the page, which happens to be the form on this page. Just try to get the correct form-element as the variable there.
Though the Manse's solution might work, use a more sensible way and assign an id to the form and since you're using jQuery anyway, retrieve the form with var frm = $(#formid); Not only is it easier to write, it's much more easier to read by you and everybody else.
When loading script via AJAX, you don't have DOMReady event anymore. In other words, when you want to execute your script on AJAX load, you should use self-invoked functions.
Wrap your ajax-loaded script inside a function like this:
(function(){
// Do what you want to do here.
})();
See if that solves the problem?