Reputation: 725
In my form, I have a input tag
& a select tag
. My input tag
will always have a link be pasted in, while my select tag
will have all domains that user has added to their account.
My form:
<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>
What I want to achieve is, when user paste a link into input#link
, if the link contains one of my select options
text, that option
will be selected.
For instance:
1) User paste inn https://www.facebook.com/officialstackoverflow/
& option
that has facebook.com as its text, will be selected.
2) User paste inn https://www.w3schools.com/html/html_forms.asp
& since none of my options
has www.w3schools.com as its text, nothing will be selected.
Upvotes: 0
Views: 176
Reputation: 2672
This is how you can do it in javascript if jQuery is not required, for somebody who is just learning.
function handleDropDown(data) {
var elem = document.getElementById('user-domains');
var optionList = elem.options;
for (var i = 0; i < optionList.length; i++) {
var currentOption = optionList[i];
if (data.indexOf(currentOption.textContent) >=0) {
elem.selectedIndex = currentOption.index;
break;//Exit the loop ASAP
}
}
}
<form action="/action">
# Link will be paste here
<input type="text" name="link" id="link" onchange="handleDropDown(this.value)">
# 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>
Upvotes: 1
Reputation: 579
The little function below should do exactly what you want.
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());
}
});
}
With onChange event as follows
<input onchange="change()" type="text" name="link" id="link">
check out the JSFiddle
Edit
I also created a JSfiddle for the onPaste
event. Because the onPaste
event fires before the value in the input is updated I had to use a setTimeout
to make sure the change function is run after the input has changed.
<input onpaste="setTimeout(function(){change()},0)" type="text" name="link" id="link">
Updated JSFiddle for the onpaste event.
Upvotes: 1
Reputation: 139
Test this:
if (str_link.toLowerCase().indexOf("facebook") >= 0) {
// select facebook option
// ... else if(other options) ...
// ...
Upvotes: 1