如何动态创建一个包含输入字段值

时间:2017-12-12 22:39:05

标签: javascript jquery twitter-bootstrap

我正在检查输入字段是否为空,如果为空,则显示一个带有消息的按钮(谷歌搜索),如果它有一些值,则显示另一个按钮(更新记录)和消息。

我的元素:

  • 输入字段
  • 按钮1(字段为空====>搜索)
  • 按钮2(字段不为空====>更新信息)

目前我可以看到我在inspect元素中创建的2个按钮,看起来很糟糕。

我已经复制了下面的代码,谢谢!



<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
        /* #googlesearch{display:none;}
        #updateinformation{display:none;}
        #emptyform{display:none;} */
</style>
</head>
<body>

<div class="container">

  <div class="form-group">
    <label >Company name:</label>
    <input onload="checker()" onkeydown="checker()" onchange="checker()" onkeyup="checker()" onfocus="checker()" class="form-control" id="txtcompany" value="dgfsd" >
   
    <div id="txtinformator">

        <small id="emptyform">Your form is empty, we recommend </small><br/>
        <button  id="googlesearch" class="btn btn-xs btn-primary">Search on Google</button>
     
        <button id="updateinformation" class="btn btn-xs btn-success">Update Information</button>

   </div>
    
  </div>
</div>

<script>


$( document ).ready(function() {
    $('#googlesearch').hide();
    $('#updateinformation').hide();
    $('#emptyform').hide();
});
// $( document ).ready(function() {
//     if($('#txtcompany').val() == ""){
           
//             $('#googlesearch').show();
//             $('#emptyform').show();
//         }
//         else if (!$('#txtcompany').val()){
//             $('#updateinformation').show();
//         }
//         else {
//             $('#googlesearch').hide();
//             $('#emptyform').hide();
          
//         }
// });
function checker(){
    if($('#txtcompany').val().length === 0){
           
        $('#updateinformation').hide();
        $('#googlesearch').show();
            $('#emptyform').show();
        }
        else if (!$('#txtcompany').val()){
            $('#updateinformation').hide();
        }
        else {
            $('#emptyform').text('We suggest that you update this information.');
            $('#updateinformation').show();
            $('#googlesearch').hide();
           
            
        }
}


</script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用javascript创建动态元素 例如

var myButton = document.createElement("<button style='background-color:yellow;' class='btn btn-default'> 
   MyButton</button>
");