根据输入文本更改按钮的URL

时间:2017-08-21 07:33:29

标签: javascript jquery html

我用按钮创建了表单字段。

我需要根据在姓氏字段中输入的数据更改按钮的URL。预订参考字段不会影响网址

示例:用户输入" John"在姓氏字段中,该按钮应具有网址:http://www.john.com

示例:用户输入" Henry"在姓氏字段中,该按钮应具有网址:http://www.henry.com



<form>
  <p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
  <input type="text" placeholder="Last name *" name="lastname">
  
  
  <input type="text" placeholder="Booking Reference *" name="ref">

  <a href="http://localhost:8888/ek/booking/" class="btn btn-info" role="button">Retrieve booking</a>
  
  
</form>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以在blur上使用lastname事件来实现此目的,

$('input[name=lastname]').on('blur', function(){
debugger
   var lastName = $('input[name=lastname]').val()
   //check if last name is there
   if(lastName.length !== 0){
      var link = 'http://www.'+ lastName +'.com';
      $('.btn.btn-info').attr('href',link);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
  <input type="text" placeholder="Last name *" name="lastname">
  
  
  <input type="text" placeholder="Booking Reference *" name="ref">

  <a href="http://localhost:8888/ek/booking/" class="btn btn-info" role="button">Retrieve booking</a>
  
  
</form>

答案 1 :(得分:0)

我在ES6风格中的回答:

https://codepen.io/powaznypowazny/pen/GvxGMY

function retrieveURL() {
  const anchor = document.querySelector('.btn.btn-info');
  const input = document.querySelector('input[name=lastname]');

  input.addEventListener('keyup', () => {
      let value = input.value.toLowerCase();
      anchor.href = `http://www.${value}.com`;
  });
}
document.addEventListener("DOMContentLoaded", function(event) {
  retrieveURL();
});

答案 2 :(得分:0)

试试这个:

     $(document).ready(function()
            {
              $('.btn btn-info').click(function() {
              var value = $("input[name='lastname']");
       if(value.length > 0)
        {
              var hrefVal = $('a').attr('href');
              hrefVal.replace('example' , value);
              $('a').attr('href' , hrefVal);
        }
            });
            });

&#13;
&#13;
<form>
  <p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
  <input type="text" placeholder="Last name *" name="lastname">
  
  
  <input type="text" placeholder="Booking Reference *" name="ref">

  <a href="http://www.example.com" class="btn btn-info" role="button">Retrieve booking</a>
  
  
</form>
&#13;
&#13;
&#13;