【问题标题】:how i can set value to input text box programmatically in jquery我如何设置值以在 jquery 中以编程方式输入文本框
【发布时间】:2016-06-27 18:59:21
【问题描述】:

我通过单击按钮将地址图像文件设置为文本框,这可以正常工作。

我需要一个侦听器来从文本框中获取值并显示警报。我不需要使用更改事件我不使用函数插入键盘值

$("#add").click(function(){
   $("input").val('http://localhost/afa/uploads/source/error-img.png'); 
});

插入地址文件后,我会显示带有内容值输入的警报

var val = $("#fieldID4").val();
files2.push({src:val});
updateList2(files2.length-1);


  function updateList2(n) {
    var e = thumb.clone();
    e.find('img').attr('src',files2[n].src);
    e.find('button').click(removeFromList).data('n',n);
    gallery.append(e);

    function removeFromList() {
        files2[$(this).data('n')] = null;
        $(this).parent().remove();
    }    
}

【问题讨论】:

  • 你试过“oninput”事件吗?这是您可以阅读的链接:developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/…
  • 这项工作是用键盘实时输入的
  • 无法通过程序识别更新
  • 请显示完整的代码上下文。看起来您在另一个函数中定义了 2 个函数,并且不清楚您曾经在哪里调用这些函数

标签: javascript jquery html css


【解决方案1】:

我通过使用 onchange 事件解决了这个问题

[http://www.w3schools.com/jsref/event_onchange.asp][1]

   <input  id="fieldID4" type="text" onchange="myFunction()" value="" >

function myFunction() {
    var val = document.getElementById("fieldID4").value;

files2.push({src:val});
updateList2(files2.length-1);


}

【讨论】:

    【解决方案2】:

    正如fire event on programmatic change 中所述,您可以执行以下操作:

    window.onload = function (e) {
      var myInput = document.getElementById('myInput');
      Object.defineProperty(myInput, 'value', {
        enumerable: true,
        configurable: true,
        get: function(){
          return this.getAttribute('value');
        },
        set: function(val){
          this.setAttribute('value', val);
          var event = new Event('InputChanged');
          this.dispatchEvent(event);
        }
      });
    }
    
    $(function () {
      $('#myInput').on('InputChanged', function(e) {
        alert('InputChanged Event: ' + this.value);
      });
    
      $('#myInput').on('change', function(e) {
        alert('Standard input change event: ' + this.value);
      });
    
      $('#btn').on('click', function(e) {
        e.preventDefault();
        var newValue = $('#newInput').val() || 'NewText';
        $('#myInput').val(newValue);
      })
    });
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    
    <form>
        Original Input: <input id="myInput"><br>
        Write here....: <input id="newInput"><br>
        <button id="btn">Change Input Text</button>
    </form>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 2018-11-25
      • 2013-09-25
      • 2017-03-01
      • 2012-09-20
      相关资源
      最近更新 更多