0

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);
  });
Clinton Green
  • 9,697
  • 21
  • 68
  • 103
  • "*I understand that when the script first runs these values will be blank because they haven't been filled out by the user yet*". That's it. Your variables contain empty strings. jQuery does not magically get you live values when referring to strings. You'll have to tell it to do that. – Bergi Mar 08 '16 at 19:51
  • :( if only jQuery worked this way. Life would be simpler. – Clinton Green Mar 09 '16 at 00:38

1 Answers1

0

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);
});
Community
  • 1
  • 1
Clinton Green
  • 9,697
  • 21
  • 68
  • 103