简体   繁体   English

如何在使用Javascript单击提交时传递用户在表单操作中输入的URL

[英]How to pass URL entered by user in form action on click of submit using Javascript

<body>
    <form name="testarea" method="post" action="?URL">
        <input type="text" id="test1" name="URL"/>
        <input type="submit" value="Submit"/>
    </form>
</body>

Now I want to: 现在我要:

  1. Use the value entered by the user in the text box for the URL 使用用户在文本框中输入的值作为URL
  2. For passing to form action='' on click of Submit . 单击“ Submit action=''以传递给表单action='' This need that same URL when passed on Submit will launch the URL in the same iFrame. 当传递给Submit时,需要相同的URL才能在同一iFrame中启动URL。

You can use jQuery to set the action attribute of your form as follows: 您可以使用jQuery来设置表单的action属性,如下所示:

var url = $("#test1").val();
$(form).attr("action", url)

If you are unable to use jquery you can refer to the following post: 如果您无法使用jquery,可以参考以下文章:

http://netfactory.dk/2007/09/28/changing-a-form-submit-url-with-javascript/ http://netfactory.dk/2007/09/28/changing-a-form-submit-url-with-javascript/

You can use method Get instead of Post 您可以使用方法Get代替Post

<body>
<form name ="testarea" Method="Get" Action="youpage.html">
<input type='text' id='test1' name='URL'/>
<input type='submit' value='Submit'/>
</form>

UPDATE: 更新:

I didn't know this is correct but you can also try like this 我不知道这是正确的,但您也可以这样尝试

<input type='text' id='test1' name=''/>
<input type='button' value='Submit' onclick="window.location.href=window.location+'?'+document.getElementById('test1').value;"/>

Place the following snippet after your form: 请将您的表格后,下面的代码片段:

function addListener(element, eventName, handler) {
    if (element.addEventListener) {
        element.addEventListener(eventName, handler, false);
    }
    else if (element.attachEvent) {
        element.attachEvent('on' + eventName, handler);
    }
    else {
        element['on' + eventName] = handler;
    }
}

var form = document.forms['testarea'];
var input = document.getElementById('test1');

addListener(form, 'submit', function () {
   var url = input.value;
   form.setAttribute('action', url);
});

I haven't tested it but it should work. 我还没有测试过,但是应该可以。 I recommend you use a library such as jquery instead of writing pure javascript. 我建议您使用诸如jquery之类的库,而不要编写纯JavaScript。 You'll make life easier and have less crossbrowser issues. 您将使生活更轻松,并且减少跨浏览器的问题。

In jQuery your code would look like this: 在jQuery中,您的代码如下所示:

​$('form[name="testarea"]').on('submit', function () {
    var url = $('#test1').val();
    $(this).attr('action', url);    
});​​​​​​​​​​​​​​​​​​​​​​

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

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