使用jQuery有一种方法可以将datalist选项值中每个单词的首字母大写

时间:2017-07-05 19:39:04

标签: jquery html attributes html-datalist

我有一个带有选项数据列表的输入表单。我想将值属性中每个单词的第一个字母大写。

我有什么:

<div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New hampshire"></option>
    <option value="New jersey"></option>
    <option value="New mexico"></option>
    <option value="New york"></option>
    <option value="North carolina"></option>
    <option value="North dakota"></option>
    <option value="Rhode island"></option>
    <option value="South carolina"></option>
    <option value="South dakota"></option>
    <option value="West virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>

我需要什么:

<div class="input-group">
<input type="text" name="q" id="s" list="states" class="form-control" placeholder="Enter State Name Here" data-bvalidator="required">
<datalist id="states">
    <option value="New Hampshire"></option>
    <option value="New Jersey"></option>
    <option value="New Mexico"></option>
    <option value="New York"></option>
    <option value="North Carolina"></option>
    <option value="North Dakota"></option>
    <option value="Rhode Island"></option>
    <option value="South Carolina"></option>
    <option value="South Dakota"></option>
    <option value="West Virginia"></option>
</datalist><span class="input-group-btn"><button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-play"></span></button>
</span>

2 个答案:

答案 0 :(得分:0)

在你的CSS中,放:

#s option {
text-transform: capitalize;
}

答案 1 :(得分:0)

未经测试,但它应该是这样的,因为替换方法看看this answer

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt) { 
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
// grep all options 
var dataList = $('#states').find('option');
// loop over them
dataList.each(function() {
    // and replace the original value
    this.value = toTitleCase(this.value);
});