简体   繁体   中英

Jquery Binding value to textbox based on user input to other textbox

I have 2 textboxes:

<table id="table1">
  <tr id="first_row">
    <td><input type="text" id="txt1"></td>
    <td><input type="text" id="txt2"><td>
  </tr>
</table>

and I have it so that one's text is populated by the content of another:

$('#txt2').keyup(function(){
  var content = $('#txt2').val();
  $('#txt1').val(content);
});

And when #txt2's content is empty, I am trying to get #txt1's content to have the string "empty".

Something like:

if ($('#txt2').val('')) {
  $('#txt1').val('empty');
}

but in real time, as opposed to just on the page load.

You could use the placeholder attribute. When the input has an empty string as it's value, browser shows the specified placeholder.

If that's not option and you want to handle it using JavaScript:

$('#txt2').keyup(function(){
  var content = this.value.trim() || "empty";
  $('#txt1').val(content);
}).triggerHandler('keyup');

Also note that for comparison you should code:

if ( $('#txt2').val() === '' ) {
   // value is an empty string
}

$('#txt2').val('') sets the value of the input and returns a jQuery object and an object is considered a truthy value in JavaScript.

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