简体   繁体   中英

Copy value from one text field to another when button clicked

I am trying to get one field to copy over to another field when a div is clicked on, and the code that I have currently is not working. It's showing '0' in field1, even though field2 is set to 1 by default.

$(document).on('click', '#button', function() {

$('#textfield1').val === "document.getElementById('#textfield2').value";

Try with:

$(document).on('click', '#button', function() {
    $('#textfield1').val($('#textfield2').val())
});

You're using an odd mix of JS and jQuery here.

Your main issue is that val() is a method, not a property. Therefore your code should look something like this:

$(document).on('click', '#button', function() {
  $('#textfield1').val($('#textfield2').val());
});

I'd strongly suggest you familiarise yourself with the jQuery documentation , specifically val() in this case.

It's showing '0' in field1, even though field2 is set to 1 by default.

You were assigning a string to $('#textfield1').val method which is why your code was not having any effect on textfield1 's value.

Make it

$(document).on('click', '#button', function() {
   $('#textfield1').val( $('#textfield2').val()); //use jquery val method
}

Generally speaking, JQuery offers only functions, and not properties (as @Craicerjack stated), hence remove that === and pass the new value as an argument, as follows:

$('#textfield1').val("yourText");

Also, you're passing a CSS selector rather than just an element ID to the Document.prototype.getElementById() function . Remove that # qualifier!

Moreover, you shoudln't be using a stringified JavaScript expression as a value, otherwise you'll get that exact JS expression as the input value. Rather, don't put those quotes around the expression, so that the interpreter will be evaluating it. Below is some working code.

$('#textfield1').val(document.getElementById('textfield2').value);

However, as @Rory McCrossan pointed out, you're using an odd mix of plain DOM and JQuery, and that makes no sense. It would be more consistent to also read the value of the other text field using JQuery, as follows:

$('#textfield1').val($('#textfield2').val());

Alternatively, you may do not need JQuery and opt for the standard DOM interfaces like in the example below:

document.getElementById('textfield1').value = document.getElementById('textfield2').value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM