简体   繁体   English

html / javascript:防止 <input> 表单提交时的清算价值

[英]html / javascript: Prevent <input> value from clearing on form submit

I have a form consisting of only one <input> element: 我有一种仅包含一个<input>元素的形式:

    <form>
            <input
                    type="text"
                    name="webpage-activity-url"
                    placeholder="URL"
                    value="[value inserted by templating engine]"
            />
            <button type="submit" class="button button-secondary" data-action="urlSubmit">
                    Submit
            </button>
    </form>

And I also have some javascript (in the form of coffeescript) which is called when the form is submitted: 我还有一些javascript(以coffeescript的形式),在提交表单时会被调用:

    onURLSubmit: (e)->
            e.preventDefault()
            # console.log('urlSubmit')
            url =  @$el.find('input[name="webpage-activity-url"]').val()
            if _.trim(url) == ''
                    return false
            if url.indexOf('//') == -1
                    url = 'http://' + url
            unless @$el.find('iframe').length > 0
                    iframe = $('<iframe />').insertAfter(@$el.find('.instructor-ui-box').first())
            @setIframeSrc url
            @$el.find('input[name="webpage-activity-url"]').val('')

Here is the same function compiled to javascript, in case you are not familiar with coffeescript: 如果您不熟悉coffeescript,以下是编译为javascript的相同函数:

WebpageActivityLayout.prototype.onURLSubmit = function(e) {
  var iframe, url;
  e.preventDefault();
  url = this.$el.find('input[name="webpage-activity-url"]').val();
  if (_.trim(url) === '') {
    return false;
  }
  if (url.indexOf('//') === -1) {
    url = 'http://' + url;
  }
  if (!(this.$el.find('iframe').length > 0)) {
    iframe = $('<iframe />').insertAfter(this.$el.find('.instructor-ui-box').first());
  }
  this.setIframeSrc(url);
  return this.$el.find('input[name="webpage-activity-url"]').val('');
};

Here is my problem: when the form is submitted, the value that the user enters into the <input> element of the form is cleared and returned to the value specified by the placeholder attribute of the input element. 这是我的问题:提交表单后,用户输入到表单的<input>元素中的值将被清除,并返回到由input元素的placeholder属性指定的值。 I would like to prevent this behavior. 我想防止这种行为。 I tried stepping through the javascript function, and I noticed that the value of the input element is reset when the onURLSubmit function returns . 我尝试逐步执行javascript函数,并注意到当onURLSubmit函数返回时,输入元素的值被重置。 So I don't really know how to prevent this through javascript. 所以我真的不知道如何通过javascript防止这种情况。

This line... 这条线...

@$el.find('input[name="webpage-activity-url"]').val('')

...is setting the value to '' ...正在将值设置为“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM