gpt4 book ai didi

javascript - jQuery - 根据输入链接中粘贴的链接选择一个选项

转载 作者:行者123 更新时间:2023-11-28 18:00:57 27 4
gpt4 key购买 nike

在我的表单中,我有一个输入标签和一个选择标签。我的输入标签将始终粘贴一个链接,而我的选择标签将包含该用户的所有已添加到他们的帐户。

我的表单:

<form action="/action">
# Link will be paste here
<input type="text" name="link" id="link">

# User will select one of their domains
<select id="user-domains">
<option value="1">google.com</option>
<option value="2">facebook.com</option>
<option value="3">stackoverflow.com</option>
<option value="4">github.com</option>
</select>

<input type="submit" value="Submit">
</form>

我想要实现的是,当用户将链接粘贴到 input#link 中时,如果链接包含我的选择选项之一文本,将选择该选项

例如:

1) 用户粘贴有 facebook 的 https://www.facebook.com/officialstackoverflow/option。 com 作为其文本,将被选择。

2) 用户粘贴 inn https://www.w3schools.com/html/html_forms.asp 并且因为我没有选项www.w3schools.com 作为文本,则不会选择任何内容。

最佳答案

下面的小函数应该完全满足您的需求。

function change () {
input = $('#link').val();

// Loop through all the options
$('#user-domains option').each(function(){

// Check if the input string contains the text from the current option
if(input.indexOf($(this).html()) >=0){
// Set the correct value to the select box
$('#user-domains').val($(this).val());
}
});
}

与onChange事件如下

<input onchange="change()" type="text" name="link" id="link">

查看 JSFiddle

编辑

我还为 onPaste 创建了一个 JSfiddle事件。因为onPaste在更新输入中的值之前触发事件我必须使用 setTimeout以确保更改函数在输入更改后运行。

<input onpaste="setTimeout(function(){change()},0)" type="text" name="link" id="link">

已更新JSFiddle用于 onpaste 事件。

关于javascript - jQuery - 根据输入链接中粘贴的链接选择一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com