How to use the same variable in two different jQuery events? - javascript

I am working on a rating system and want to pull up each rating value by the jquery.
For this purpose I am doing like this, but I am unable to get previous event variable value into next event.
var r1Rating;
$(".rating-input").on("click",function(){
//alert($(this).attr("id"));
var r1=$(this).attr("id");
var r1Array=r1.split("-");
//alert(r1Array[r1Array.length-1]);
var r1Rating=parseInt(r1Array[r1Array.length-1]).toFixed(2);
$("#total_rating").html(r1Rating);
var r1Rating=r1Rating;
});
$(".rating-input1").on("click",function(){
alert(r1Rating); //I want to get value here
});
Any help, suggestion would be appreciated. Thanks

Even though you have a r1Rating in the external scope, since you are using var r1Rating in the click handler, you are creating a new locally scoped variable in the click handler. So any changes you make to the variable will be visible inside that method only and the variable in the external scope will not be updated.
var r1Rating;
$(".rating-input").on("click", function () {
//alert($(this).attr("id"));
var r1 = $(this).attr("id");
var r1Array = r1.split("-");
//should not use var here
r1Rating = parseInt(r1Array[r1Array.length - 1]).toFixed(2);
$("#total_rating").html(r1Rating);
});
$(".rating-input1").on("click", function () {
alert(r1Rating); //I want to get value here
});

The code below should be changes, since in this instance, you created a new r1Rating variable in a scope, which means that this was a different variable from the global one outside.
var r1Rating=r1Rating;
This should be changed to:
r1Rating=r1Rating;

Related

How to pass `$(this)` as parameter to a "callready" function in Javascript

The leanModal function triggers a modal with some parameters. One of this parameters is a function (ready) that will be executed once the Modal is open. The point is, I need to do some stuff inside that function (ready) just with the element (tag) which triggered the modal, so I need to pass $(this) as parameter to that function. The leanModal() function is provided by MaterializeCss which's the framework that I'm using.
I've been trying this, but thisTag is always undefined. I also have tried to pass directly $(this) to the function, but it also doesn't work at all, it's still undefined. So, how can I reach this?
$('.modal-trigger-editMedic').leanModal({
thisTag: $(this),
ready: function(thisTag){
var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
$('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});
Following the source code, .leanModal supports a ready function (which is triggered once the modal is visible) but doesn't bind or send the element which triggered the modal, the easiest way to fix this is to store a reference outside. To do so, you need to iterate over the triggers yourself instead of relying on that functionality of provided by this jQuery plugin.
Like so:
var $surname = $('#surname'); // you should store the selector as a reference
// outside the loop for better performance
$('.modal-trigger-editMedic').each(function() {
var $this = $(this); // this is the current item in the set of elements,
// therefore our trigger element
// EDIT: using var makes this a local variable
$this.leanModal({
ready: function() {
var refereeNum = $this.siblings("[name*='refereeNumToEdit']" )[0].value;
$surname.val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});
});
When you are inside the leanModal it becomes this. Try setting a var to $(this) and pass that through.
var that = $(this);
$('.modal-trigger-editMedic').leanModal({
thisTag: that,
ready: function(thisTag){
var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
$('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
}
});

JQuery change variable value outside the function

I want to change the value of my "clients" variable from outside the function, with the one from inside the function(which changes when I select something), and I dont know how to do that. Please help
This is my code code
<script>
var clients;
$('#clients').on('change',function(e)
{
console.log(e);
var clients = e.target.value;
});
document.write(clients);
</script>
var keyword creates a local variable. Remove it to have access to variable from the outer scope:
var clients;
$('#clients').on('change', function(e) {
clients = e.target.value;
});
However, you should keep in mind that alert(clients) in your last line will always display undefined as the change event will be triggered later when the actual event will fire.
by using var inside the function you're redefining it in that scope, just remove var inside the function
var clients;
$('#clients').on('change',function(e)
{
console.log(e);
clients = e.target.value;
});
alert(clients);

passing the value from a textbox to another function

I have an html textbox and get the value from it with the following code:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
I then attempted to pass that value to a different function
function loadPdf(pdfPath) {
var pdf = PDFJS.getDocument(pdfPath);
return pdf.then(renderPdf);
}
loadPdf(value);
But the value isn't being passed. I then attempted to do the following:
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
to see if the value was displayed, but that didn't work either (didn't get any output)
EDIT: I do get an error in the console:
ReferenceError: $ is not defined
And if I remove the $ it says ('#getTextBoxValue).on is not a function
$ is a reference to jQuery. This works for me if jQuery is included:
<input id="textbox1"></input>
<button id="getTextBoxValue">Get value</button>
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
JSFiddle example
If you wanted to do it without jQuery, use document.getElementById("textbox1").value; and add the onclick either inline or via normal javascript also:
document.getElementById("getTextBoxValue").onclick = function(){
var value = document.getElementById("textbox1").value;
alert('The Value in Textbox is '+value);
};
After you get that to work, just replace the alert with loadPdf(value);
the var value is local to the onclick function, so has to be accessed inside of that function or made global.
Once you have jQuery loaded on the page, it should be as easy as calling your helper function inside the click event.
$('#getTextBoxValue').on("click", function(){
loadPdf( $("#textbox1").val() );
});
You've tagged this as javascript but The code you are using to grab your values and bind your functions is jQuery. The error you are getting is telling you that there is no mapping of "$" to jQuery. If you want to make sure you have the reference set, you can replace the $ with the string "jQuery" so $('someselector') becomes jQuery('someselector').
BUT, this may just be the console you are using. You have another error which is probably the issue. You have this:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
In this your value is locally scoped in the callback. Unless you do something with it before the function exits, you lose it completely. If you intend to do something with it later, you have to globally scope it by bringing it out of any function definition.
var value;
...
function someFunction(){
...
$('#getTextBoxValue').on("click", function(){
value = $("#textbox1").val();
});
}
The reason for this is due to scope.
You are defining your variables within the function with var.
$(document).ready(function() {
var value;
var pdf;
var value;
/* Then do your functions. This will make then global.
When you type then within your functions do not put var in front of them */
});

Javascript: Passing variable from function to function

I'm new to Javascript and I have a problem passing a variable from function to function:
$(document).ready(function () {
$('input[type=checkbox]:checked').removeAttr('checked');
var filename = document.getElementById("Tagg").value;
var checkboxesH = $('input[type="checkbox"][name="tags[]"]');
checkboxesH.change(function () {
$('input[type="text"][name="tags"]').val(filename);
var current = checkboxesH.filter(':checked').length;
});
});
in the checkboxesH.change function, filename is always null! why? When the page opens, there is a string in the textfield tags.
Thank you.
Javascript passes the value of the variable at the time of the function creation. To fix this problem you should simply call
document.getElementById("Tagg")).value
in your .change() function directly. This way, it will reflect the state at change time, not when the change event handler was created.

how to get a variable over to a function?

i want to get a variable (which is set when a link is clicked) over to a function and show it as a pop out.
the code as shown below:
$('a#link1').click(function(e){
e.preventDefault();
var value = 'true';
});
function exe(){
alert(value);
}
when the function is executed , all i get is value is undentified.
So anyone knows a way around it?
Variables have scope, you define the value variable in the scope of the onclick closure, and it wont be accessible outside it.
The following would work:
var value = false; //Define in the global scope
$('a#link1').click(function(e){
e.preventDefault();
value = false; //Use in a local-scope is legal.
});
function doSomething()
{
alert(value);
}
However having many global variables will make your project hard to maintain, and there are other more clean solutions available. In general i'd recommend you to read a proper book on programming though :)
Just make the variable global, or better yet "attach" it to the element using the .data():
$('a#link1').click(function(e) {
e.preventDefault();
$(this).data("value", "true");
});
Then you can always check for this:
function exe() {
alert($('a#link1').data("value"));
}
Note that it was added in jQuery 1.2.3 guess that by now it doesn't really matter though.

Categories

Resources