我希望最好用jquery编码,但通常情况下,javascript对我来说仍然很好。
问题是这样的:我在同一页面上有一个文本区域和一个下拉菜单。我可以通过键入或粘贴文本将文本填充到文本区域中。每行的文本区域包含以逗号分隔的电子邮件和姓名:例如:例如
email1@xyz.com,理查兹·
email2@abc.com
EmilY34@yahoo.com , 艾米丽·怀特斯
Juniorpope4u@gmail.com , 少年
Mike87@yahoo.co.uk,
Ademola45thus@gmail.com,阿德莫拉·埃里克森
等(请注意,逗号可以在任何地方,甚至可以不存在)我希望下拉菜单自动填充在文本区域找到的电子邮件的域名值。注意:下拉列表中不应有重复的列表,并且列表应在下拉列表中按字母顺序排列在我的示例中,下拉列表将填充如下:
都
abc.com
gmail.com
xyz.com
yahoo.com
yahoo.co.uk
默认选定的下拉项的值为 ALL。请我知道如何在php中执行此操作,但对使用javascript或jquery一无所知。另外,php必须刷新页面才能工作,但javascript不需要重新加载页面
嗨,请检查 https://jsfiddle.net/pykmgyyt/5/...
jQuery
$(document).ready(function(){
var arr= new Array();
arr[0]="ALL"; //Setting fist element of the array to ALL
$('.btnUpdate').on('click', function(){
var newEmails=new Array();
var newEmails=$('.taEmails').val().split(/[ ,rn]+/); // get text area value and split text whenever jq encounters comma, space or newline and storing it into an array
/* Travese through newEMails array and push string which contains '@' in to arr array */
$.each(newEmails, function(i){
if (newEmails[i].indexOf('@') > -1){
arr.push(newEmails[i].substring(newEmails[i].indexOf("@") + 1)); /* Get only the domain names*/
console.log(newEmails[i]);
}
});
// check for duplicates
var result = [];
$.each(arr, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
arr= result;
$('.ddEmails').empty(); // Empty dropdown
arr.sort(); // sort array
/*Append new array*/
$.each(arr, function(i){
$('.ddEmails').append("<option>"+arr[i]+"</option>");
//console.log(arr[i]);
}); /// arr each
}); // click
});
- 用逗号和换行符分隔
-遍历每个拆分的字符串
-
检查是否有@符号
-
找到域名并返回
-在选择框中显示
.HTML
<textarea id="emails" onkeyup="finddomain();">
email1@xyz.com, Richards Dough
email2@abc.com
EmilY34@yahoo.com , Emily Whites
Juniorpope4u@gmail.com , Junior
Mike87@yahoo.co.uk,
Ademola45thus@gmail.com, Ademola Erickson
</textarea>
<select id="add_domain" name="add_domain">
</select>
爪哇语
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
function extractDomain(url) {
var ind=url.indexOf("@");
if (ind > 0)
{
var domain = url.substr((ind+1));
return domain;
}
else
return '';
}
function finddomain()
{
// You can do the below parts on javascript event
data = document.getElementById('emails').value;
var arr = data.split(/[n,]+/); //data.split('n');
var arrayLength = arr.length;
var sel = document.getElementById("add_domain");
for (var i = 0; i < arrayLength; i++) {
var domain = extractDomain(arr[i].trim());
if (domain != '' && $("#add_domain option[value='"+domain+"']").length == 0)
{
var option = document.createElement("option");
option.text = domain;
option.value = domain;
sel.appendChild(option);
}
}
}
</script>
下面的部分是提取多个事件的域
<script type="text/javascript">
$(document).ready(function() {
$('#emails').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
finddomain();
});
});
</script>