将值从输入文本绑定到按钮值jquery

时间:2016-02-04 07:45:06

标签: javascript jquery

如何从输入文本框绑定按钮值。 当我们点击按钮时,按钮值将显示在文本框中,如果我们从输入文本框更改值也必须更改所选按钮值..

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>val demo</title>
  <style>
  button {
    margin: 4px;
    cursor: pointer;
  }
  input {
    margin: 4px;
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>
  <button>Feed</button>
  <button>the</button>
  <button>Input</button>
</div>
<input type="text" value="click a button">
 
<script>
$( "button" ).click(function() {
  var text = $( this ).text();
  $( "input" ).val( text );
});
</script>
 
</body>
</html>

2 个答案:

答案 0 :(得分:2)

试试这个

&#13;
&#13;
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>val demo</title>
  <style>
  button {
    margin: 4px;
    cursor: pointer;
  }
  input {
    margin: 4px;
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>
  <button>Feed</button>
  <button>the</button>
  <button>Input</button>
</div>
<input type="text" value="click a button">
 
<script>
var button = $();
$( "button" ).click(function() {
  button = $(this);
  var text = $( this ).text();
  $( "input" ).val( text );
});
$("input").on("input", function(){
    button.html($(this).val());
});
</script>
 
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>val demo</title>
  <style>
  button {
    margin: 4px;
    cursor: pointer;
  }
  input {
    margin: 4px;
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>
  <button>Feed</button>
  <button>the</button>
  <button>Input</button>
</div>
<input type="text" value="click a button">
 
<script>
var actualButton;
$( "button" ).click(function() {
  actualButton = $(this);
  var text = $( this ).text();
  $( "input" ).val( text );
});
$("input").on('keyup', function(e){
  if(actualButton === undefined)
    return;

  actualButton.text($(this).val());
});
</script>
 
</body>
</html>
&#13;
&#13;
&#13;

编辑:哦,某人更快;)

相关问题