Undefined JS alert - javascript

I've got an a-tag which reads as this: (and there are number of a-tags being dynamically populated as this stays inside a PHP loop.)
echo "<a onclick='trygettheid();' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
and the JS function looks like below.
function trygettheid()
{
var myvariable = $(this).attr('id');
alert(myvariable);
}
The issue is when a click is triggered, the alert says 'undefined' instead of the desired output of 'main'
Am I missing anything here?

Inside the function this does not refer to the clicked element it may be window object. To fix it pass the reference as an argument to the function. Although there is no need to use jQuery since id can be get from element id property.
PHP :
echo "<a onclick='trygettheid(this);' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
// ------^------
JS :
function trygettheid(ele){
// -----^-----
var myvariable = ele.id;
// ---^--^----
alert(myvariable);
}

Related

Cannot modify the value of a node in a onclick called function

I set the arguments of my function called on onclick event with PHP and I also pass "this" ( the button ) as an argument so that in my function I access the closest <td> node and change its value.
However, I can't change the value of the node.
I get
is not a function
error each time I try to modify it.
PHP code :
echo "<tr><td>";
echo "<button onclick='updateValue($index,$byte,this)'></button>";
echo "<td>".$byte."</td>";
echo "<td>".$comment."</td>";
echo "</tr>";
And my JS function there :
function updateValue(index,byte,button){
$.ajax({
url : 'commentrefresh.php',
type : 'GET',
data : 'bytenumber=' + byte +"&byte_id=" +index,
datatype : 'text',
success : function(data){
button.closest('tr').lastChild.val(data)
}
})
}
Check this fiddler and the way I get the lastChild td node.
https://jsfiddle.net/aqmtjs8k/
$(button).closest('tr').find('td:last-child')
And if you want to write inside the last td you should use .html() and not .val()
.val() is only for inputs
Correct way: $(button).closest('tr').find('td:last-child').html(data)
As the error message says, closest isn't a function on DOM nodes.
You've tagged this question jquery, and jQuery objects do have a closest method, but you haven't wrapped the DOM node in a jQuery object.

Validate dynamic input form elements using Validator Plugin Jquery

I am using this http://jqueryvalidation.org/ jquery validation plugin.
HTML dynamic form will be like this
<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">
<a class="myfont baby_book_save" href="javascript:void(0)" onclick="validatefilesizeform('save')" >Save</a>
</form>
My JS Code will be like this
<script type="text/javascript">
var validator="";
$(document).ready(function(){
var max_length_rules= <?php echo json_encode($valid_rules); ?>;
validator=$("#baby_book").validate();
$.each(max_length_rules,function(k,v){
$.each(v, function(key, value){
$('input[id="'+key+'"]').rules('add',"required");
});
});
});
function validatefilesizeform(type)
{
if(type == 'save')
{
document.baby_book.sec_submit.value="save";
if(validator.form())
{
document.baby_book.submit();
}
}
</script>
While applying dynamic rules like that it doesn't validate the form.
In console it displays this error
Uncaught TypeError: Cannot read property 'form' of undefined
Can anyone help me how to add dyanmic rules . Thanks.
That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, i.e runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.
The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form(), that variable is already undefined. It will be initialized later, inside the $(document).ready().
To get the expected behavior, and avoid the error, you must change the onclick handler to this one:
`onclick="function() { validatefilesizeform('save') }"`
In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.
To make it even more clear:
// This is the value returned by the function evaluation:
validatefilesizeform('save')
// This is a function
function() { validatefilesizeform('save'); }
So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

JSON.stringify in js

How do I get reference of the <div> id and title from a external JS by using the code below:
function recordedEvent() {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
alert(JSON.stringify(o));
}
The function is called in the HTML with a onclick called box1().
Code in CplTemplateSetup.js is where I want to run the function from into the HTML:
content_left_30_four_click_images_right_70_head_content_template.html
Any help would be appreciated.
P.S.: JSON data (zip archive)
Well the most obvious problem is that you don't have a closing parenthesis after your callback.. otherwise the code looks good
Edit
window.lastClickedBoxData = {}; // just reassign that within your function
or
window.runThisWhenClicked = function () {
var v_Id = $(this).attr('Id');
var v_Title = $(this).attr('Title');
var o = { Title : v_Title, ObjectId : v_Id };
};
then just
$(".box").click(window.runThisWhenClicked);
I don't think that the problem that you're facing would be apparent to anyone who doesn't view your code.
You defined a function within a script tag, in the html, and called that function in the onclick attribute of the box being clicked on. To that function, this refers to the box that was clicked on. From there, you call a function within an external js document. In that function, this refers to the window object. In other words, for the code that you posted, $(this) is a jquery instance of the window object which doesn't have the attributes that you're looking for, such as id and title, so they're blank.
To see what I'm talking about open the console and add the following line of code to each of your functions:
console.log(this);
If you're having trouble doing that, the following code should work as well, but it's not as good for debugging:
alert(this);
You need all of your code to be in the html script tag or in the external document. Also, you shouldn't define the function to be called during a click event using onclick within the html. It's better to do it using javascript or jquery so that your javascript is completely separate from your html.
EDIT: You shouldn't update your question with an answer. You should edit the original question with this information so that anyone having a similar problem can find the solution. I'd have commented on the answer directly, but I don't have the reputation to do this.

How to get global variable value to ajax

i am trying to get the global variable value inside ajax,jquery function.
here i am using this code..
code:
<script type="text/javascript">
var id;
function refreshRecord(id)
{
alert(id);
}
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
alert("id is"+fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){$("#div1").html(data);},
error:function(data){$("#div1").html("It was a failure !!!");}
});
});
});
</script>
Onclick one submit button i am calling the javascript function
<input type="radio" name="submit" value="submit" onclick="refreshRecord(this.value)">
Here what i want to get is, i have declared the global variable id in script tag,
when i click on radio button the onclick event calls the javascript function refreshRecord(id) with one parameter 'id'
now that id value will be set to some value. now i want to get that variable value inside jquery function and i want to assign it to
var fileId = id;
but when i did the above code and click button.
in alert it is showing the first value correctly(i.e the alert from javascript is coming correctly) but the alert from the ajax,jquery is coming is as undefined or [Object Object]
How can i resolve this??
You need to assign the value passed to the function to the global variable id. Currently you are not assigning it. The parameter id of the function is just local to the function , it is not the same global one and the global variable id is still undefined.
Just modify as below,
var id;
function refreshRecord(value)
{
id = value;
alert(id);
}
You should put the value from the field inside the global variable:
var id;
function refreshRecord(inputValue)
{
id = inputValue;
alert(id);
}
Because if you do this:
function refreshRecord(id)
{
alert(id);
}
the id global variable won't be accessible inside the refreshRecord function because of a name conflict inside the function scope. Please read about scope to understand:
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
The argument we pass inside a function acts as a local variable to that function. So in your function you are actually creating a local variable and setting the value.
Try this instead -
var id;
function refreshRecord() {
id = $("input:radio").val();
}
Give an id to have better selector for radio button.

jquery pass value into function AFTER function?

I am new to javascript & jQuery. I'm trying to create a feature for my site that let's people display badges they have earned on their own site (and I would supply a bit of code they could just copy/paste). I had someone help me with the javascript and I have it working perfectly, but I can't find any jQuery documents that explains it to me?
<script type="text/javascript">
(function(id) {
// include js via php file with the id in as a parameter
})("myid");
</script>
The id is passed in the area labeled "myid", in jQuery can you pass in a static variable this way? When I try to delete ("myid") and change it to var id = 'myid', the function no longer works.
The occurrence of "myid" in the code you are showing is not a static variable. It is a string literal that is being passed as an argument to an anonymous function. The anonymous function is declared and then is immediately getting called.
If you are wondering why the programmer wrote the JavaScript the way they did. The following might help.
Both of the examples below will display "myid" in an alert:
Example 1:
<script type="text/javascript">
var id = 'myid';
alert(id);
</script>
Example 2:
<script type="text/javascript">
(function(id) {
alert(id);
})('myid');
</script>
The first example declares "id" as a variable. It is a global variable and is actually added as a property to the window object. The second example defines an anonymous function and immediately calls it, passing in 'myid' as the value of the "id" parameter. This technique avoids using a global variable.
Of course, you could also avoid the global variable by doing the following:
<script type="text/javascript">
(function() {
var id = 'myid';
alert(id);
})();
</script>
If you stick "myid" in a variable and then pass in that variable, it'll work. Like this:
var memberID = "myid";
(function(id) {
// include js via php file with the id in as a parameter
})(memberID);
If you say this...
(function(id) {
// include js via php file with the id in as a parameter
})(var id = 'myid');
...you're attempting to stick a variable declaration in a function call, which won't work. That's why declaring the variable above and apart from the function call won't throw any errors.

Categories