jQuery accessing updated values from variables on different events - javascript

I have a function which copies the values of a group of inputs to another group of inputs if the user clicks a button.
The function works fine but I'm having trouble with the vars I'm using to get the information. I want to use global variables because I want to use the same variables later on but it only works when I wrap those vars inside the function.
I've posted the two scenarios where it's working and not working below. Can anyone explain why I cannot access the correct value at that given time using a global variable?
EDITS: The 3 elements #admin-name, #admin-email and #admin-number are all present in the DOM when the script is called, as I am doing everything with document ready. I understand that when the script first runs these values will be blank because they haven't been filled out by the user yet. What I don't understand is why can't jQuery get the value once it has been filled out and I call the variable on the click function.
Not Working
var contactName = $('#contact-name').val();
var contactEmail = $('#contact-email').val();
var contactNumber = $('#contact-number').val();
$(".step-two .copy-details").on('click', function(){
$('#admin-name').val(contactName);
$('#admin-email').val(contactEmail);
$('#admin-number').val(contactNumber);
});
Working
$(".step-two .copy-details").on('click', function(){
var contactName = $('#contact-name').val();
var contactEmail = $('#contact-email').val();
var contactNumber = $('#contact-number').val();
$('#admin-name').val(contactName);
$('#admin-email').val(contactEmail);
$('#admin-number').val(contactNumber);
});

Man I struggled with this one, this post helped flesh it out for me, jQuery Global Variable. The problem is the variable called in the click function was still getting the original value of 0. To make the variable update when a new value is added you need to declare it and then wrap it in a change function like so:
JS
// declare the variable
var contactName;
// wrap it in a change function so the value updates
$('#contact-name').on('change', function(){
contactName = $('#contact-name').val();
});
// use the variable inside the function and it will show the updated value
$('.step-two').on('click', 'button', function(){
$('#admin-name').val(contactName);
console.log('contactName = ' + contactName);
});

Related

Onclick function changes value

I want an easy way to set a variable value equal to n when function(n) runs.
Hovedkort
Prosessor
Arbeidsminne
I have this piece of HTML code. And I want the loadProdType function to change the value of a variable prodCat according to loadProdType's value. I tried the code under with and witout localstorage.setItem(loadCat, j). The js document is linked and there are no linking errors cause other pieces of code runs as it should.
var loadCat = 0
function loadProdType(j){
loadCat = j}
How can I set loadCat's value equal to loadProdType's value/parameter.
Thanks in Advance.
Edit:
Unsure how to set local storage for this but what I want the code to do is the following:
Change the value of variable prodCat according to the value of the onclick function.
Redirect to: products.html
When in products.html I run a piece of code that uses the prodCat value to choose a spesific index in an array.
All in all I just need to be able to change prodCat on one page(to the value of a funcion or with a onclick) and have it saved on the next.
Last edit
I'll create different functions for each onclick and try that with local storage.
You need either ? in the URL or local storage.
?
In main document:
location.href = "products.html?prodType=" + loadCat;
In products.html:
var loadCat = new URL(document.URL).searchParams.get("prodType");
localstorage
In main document:
window.localStorage.setItem("prodType", loadCat);
In products.html:
var loadCat = window.localStorage.getItem("prodType");

GTM javascript does not fill variables

I am trying to use predefined variables for a simple GTM javascript macro, however, the variables do not load. Why is my code not loading the variables?
code:
function () {
var value = {{Click URL}};
var begin = value.indexOf(":")+1;
var end = value.substr(-1);
return value.slice(begin,end);
}
Just a shot in the dark, but the click variables are not enabled by default. Check if they are enabled in variables/built in variables:
You'd need to set the checkbox in front of Click URL.
In the end I solved it by leaving out the "end" variable (slice automaticlly uses the last character if you do not feed it the second argument). It looks like this now:
function () {
var value = {{Click URL}};
var begin = value.indexOf(":")+1;
return value.slice(begin);
}

Dynamically changing string - correct value not being submitted?

I recently posted another question about how to add content to a string (Dynamically change string with JS?), and I made progress on that front but it seems the updated variable is not being submitted. Am I missing something?
Here is my code:
<script type="text/javascript">
var selections = 'Gender, ';
jQuery(".add-to-form").click(function () {
var title = jQuery(this).attr("title");
selections += title + ', ';
console.log(selections);
});
var ss_form = {'account': 'XYZ', 'formID': 'XYZ'};
ss_form.width = '100%';
ss_form.height = '1000';
ss_form.domain = 'app-XYZ.marketingautomation.services';
ss_form.hidden = {'field_XXXXX': selections };
</script>
This works great in that the correct values are showing up in the console log, but when I submit the form and look in SharpSpring the only value getting through is the initial variable value (Gender, ). Do I need to somehow refresh the variable value in the hidden field?
All help is appreciated, thank you!
The following line is executed on page load:
ss_form.hidden = {'field_XXXXX': selections };
This assigns the value of selections as it is at that moment. The field_XXXXX property is a separate variable that will not change when you assign a different value to selections later.
So when the click event fires, and you assign a new (longer) value to selections, then only that variable changes. It is not connected to the property above.
How to solve? Just do another assignment to the ss_form.hidden.field_XXXXX property within the click handler:
jQuery(".add-to-form").click(function () {
var title = jQuery(this).attr("title");
selections += title + ', ';
ss_form.hidden.field_XXXXX = selections; // <-------
console.log(selections);
});
I assume that ss_form.hidden is some API driven way to set a hidden input element, and that this works. If not, make sure to identify the input element that needs to get a new value, which could look like this:
$('#id_of_hidden_input').val(selections);

About a loop that creates dynamic buttons, but cannot give proper values [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript infamous Loop problem?
I am having a small issue, and it would be very nice if some of you could realize about what kind of logic is missing here, since I cannot seem to find it:
I have an array with the results of some previous operation. Let's say that the array is:
var results = [0, 1];
And then I have a bunch of code where I create some buttons, and inside a for loop I assign a different function to those buttons, depending on the position of the array. The problem is that for some reason, all the buttons created (two in this case) come out with the function assigned to the last value of the array (in this case, both would come out as one, instead of the first with 0 and the second with 1)
This is the code:
for (var i = 0; i < results.length; i++) {
var br2 = b.document.createElement("br");
var reslabel = b.document.createTextNode(Nom[results[i]].toString());
var card = document.createElement("input");
card.type = "button";
id = results[i]; // this is the problematic value.
card.onclick = newcard; // this function will use the above value.
card.value = "Show card";
divcontainer.appendChild(br2);
divcontainer.appendChild(reslabel);
divcontainer.appendChild(card);
}
As it is, this code produces as many buttons as elements in the array, each with its proper label (it retrieves labels from another array). Everything is totally fine. Then, I click the button. All the buttons should run the newcard function. That function needs the id variable, so in this case it should be:
First button: runs newcard using variable id with value 0
Second button: runs newcard using variable id with value 1
But both buttons run using id as 1... why is that?
It might be very simple, or maybe is just that in my timezone is pretty late already :-) Anyways, I would appreciate any comment. I am learning a lot around here...
Thanks!
Edit to add the definition of newcard:
function newcard() {
id = id;
var toerase = window.document.getElementById("oldcard");
toerase.innerHTML = "";
generate();
}
the function generate will generate some content using id. Nothing wrong with it, it generates the content fine, is just that id is always set to the last item in the array.
Your id is a global variable, and when the loop ends it is set to the last value on the array. When the event handler code runs and asks for the value of id, it will get that last value.
You need to create a closure to capture the current results[i] and pass it along (this is a very common pitfal, see Javascript infamous Loop problem?). Since newcard is very simple, and id is actually used in generate, you could modify generate to take the id as a parameter. Then you won't need newcard anymore, you can do this instead:
card.onclick = (function(id) {
return function() {
window.document.getElementById("oldcard").innerHTML = "";
generate(id);
};
}(results[i]));
What this does is define and immediately invoke a function that is passed the current results[i]. It returns another function, which will be your actual onclick handler. That function has access to the id parameter of the outer function (that's called a closure). On each iteration of the loop, a new closure will be created, trapping each separate id for its own use.
Before going on, a HUGE thank you to bfavaretto for explaining some scoping subtelties that totally escaped me. It seems that in addition to the problems you had, you were also suffering from scoping, which bit me while I was trying to craft an answer.
Anyway, here's an example that works. I'm using forEach, which may not be supported on some browsers. However it does get around some of the scoping nastiness that was giving you grief:
<html>
<body>
<script>
var results = [0,1];
results.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = "Show card";
document.body.appendChild(card);
});
function newcard(x) {
alert(x);
}
</script>
</body>
</html>
If you decide to stick with a traditional loop, please see bfavaretto's answer.

Jquery global variable assignment and using in javascript function

I have a global variable listId(refer the below code) declared with a default value and then I am assigning it inside the jq("#nav1 li a").click(function() But once any of the other javascript function call takes place after this one, the listId does not reflect the changed value, instead its just the default value assigned during declaration. How can I make it reflect the changed values?
thanks
listId = 'x';
var jq=jQuery.noConflict();// for avoiding conflict
jq("#nav1").click(function(){
alert(this.id);
listId = this.id; //this.id is displayed in alert message
});
function pageSwitch(){
alert('on change id : '+listId);
//when called after the click function, this does not reflect changed values
}
The code you supplied worked for me. The listId variable was successfully changed to "nav1". I've written up a little test script, which changes listId to the div's id onClick, and then uses a function to change it back to "x". It works every time. Click here to test it.
Thanks guyz for the help..actually the function was invoked on click of an h:commandLink..so each time the page got reloaded and so did the js functions...I just used the a4j:commandLink and it worked fine...I should have presented the full picture..Sorry for that..will take care next time.

Categories

Resources