从表单字段中删除单词的代码

问题描述 投票:1回答:1

我有一个jQuery表单,其中包含一个网站URL的文本字段(字段ID为:43)。当用户输入“http://”或“https://”作为URL的一部分时,我需要表单在之前或之后自动删除“http://”或“https://”部分表格已提交。

我似乎无法让这个工作。这是我尝试过的最新代码(起初,只是试图让它去除“http://”

<script type="text/javascript">
               document.getElementById("43").setAttribute("onchange", "deleteValue()");
function deleteValue() {
    var weburl = 'http://';
    var textarea = document.getElementById("43");
    var data = textarea.value;
    textarea.value = textarea.value.replace(weburl.value, "");
}
</script>

任何人都可以提供一个关于如何使其工作的建议吗?

jquery forms field
1个回答
0
投票

您可以使用.blur()事件来触发http://https://的删除

工作实例:

$(document).ready(function(){
    
    $('input').blur(function(){
        var currentText = $(this).val();
        var replacedText = currentText.replace(/^https?\:\/\//i, '');
        $(this).val(replacedText);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<fieldset>
<legend>Write a url with http:// and click elsewhere</legend>
<input type="text" name="myUrl" />
</fieldset>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.