如何使用控制台从下拉列表中选择项目?



试图在这里保持我的幽默感-我一直在试图准备代码,这将允许我使用控制台自动完成web表单的不同部分。我不能使用硒。在标记了很多进展之后(在这里的答案的帮助下),网站已经更新了(使用Bootstrap?),我的大多数命令现在都不起作用了。在这个特定的项目上,页面上有一个下拉菜单,它会显示一个颜色列表。单击一种或多种颜色将使其在输入框中被选中。我正试图通过将代码放入控制台来实现相同的目标。

我尝试重新利用我以前使用的代码,但我认为元素是完全不同的类型。有人能帮忙吗?下面是下拉菜单的代码(我不认为我需要在这里包括HTML ?):

<div class="form-group col-sm-12" element="div"> <label>colour type</label>
<select name="colourTypes[]" style="width: 100%" data-init-function="bpFieldInitSelect2MultipleElement" data-select-all="false" data-options-for-js="[2,1,5,7,6,13,12,9,10,16,4,15,3,8,11]" class="form-control 
select2_multiple select2-hidden-accessible" multiple="" data-select2-id="10" tabindex="-1" aria-hidden="true" data-initialized="true">
<option value="" data-select2-id="17">-</option>
<option value="2" data-select2-id="18">N/A</option>
<option value="1" data-select2-id="19">Red</option>
<option value="5" data-select2-id="20">Green</option>
<option value="7" data-select2-id="21">Blue</option>
<option value="6" data-select2-id="22">Magenta</option>
<option value="13" data-select2-id="23">Turquoise</option>
<option value="12" data-select2-id="24">Maroon</option>
<option value="9" data-select2-id="25">Olive</option>
<option value="10" data-select2-id="26">Yellow</option>
<option value="16" data-select2-id="27">Grey</option>
<option value="4" data-select2-id="28">Silver</option>
<option value="15" data-select2-id="29">Other/Unclear</option>
<option value="3" data-select2-id="30">Crimson</option>
<option value="8" data-select2-id="31">Dark blue</option>
<option value="11" data-select2-id="32">Light blue</option>
</select><span class="select2 select2-container select2-container--bootstrap select2-container--
focus select2-container--below select2-container--open" dir="ltr" data-select2-id="11" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--multiple" 
role="combobox" aria-haspopup="true" aria-expanded="true" 
tabindex="-1" aria-disabled="false" aria-owns="select2-colourTypes-9c-results">
<ul class="select2-selection__rendered"><li class="select2-search select2-search--inline">
<input class="select2-search__field" 
type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" 
placeholder="" style="width: 0.75em;" aria-controls="select2-colourTypes-9c-results">
</li></ul></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

</div>

是。一种方法是抓取所有选项并循环遍历它们。

然后,选择需要的选项。

const options = document.querySelectorAll('select[name="colourTypes[]"] option'); // a CSS selector
[...options].forEach((curr) => {
// Select values of 1, 5, and ''
if (['1', '5', ''].indexOf(curr.value) !== -1) {
curr.selected = true;
}
});
<div class="form-group col-sm-12" element="div"> <label>colour type</label>
<select name="colourTypes[]" style="width: 100%" data-init-function="bpFieldInitSelect2MultipleElement" data-select-all="false" data-options-for-js="[2,1,5,7,6,13,12,9,10,16,4,15,3,8,11]" class="form-control 
select2_multiple select2-hidden-accessible" multiple="" data-select2-id="10" tabindex="-1" aria-hidden="true" data-initialized="true">
<option value="" data-select2-id="17">-</option>
<option value="2" data-select2-id="18">N/A</option>
<option value="1" data-select2-id="19">Red</option>
<option value="5" data-select2-id="20">Green</option>
<option value="7" data-select2-id="21">Blue</option>
<option value="6" data-select2-id="22">Magenta</option>
<option value="13" data-select2-id="23">Turquoise</option>
<option value="12" data-select2-id="24">Maroon</option>
<option value="9" data-select2-id="25">Olive</option>
<option value="10" data-select2-id="26">Yellow</option>
<option value="16" data-select2-id="27">Grey</option>
<option value="4" data-select2-id="28">Silver</option>
<option value="15" data-select2-id="29">Other/Unclear</option>
<option value="3" data-select2-id="30">Crimson</option>
<option value="8" data-select2-id="31">Dark blue</option>
<option value="11" data-select2-id="32">Light blue</option>
</select><span class="select2 select2-container select2-container--bootstrap select2-container--
focus select2-container--below select2-container--open" dir="ltr" data-select2-id="11" style="width: 100%;"><span class="selection"><span class="select2-selection select2-selection--multiple" 
role="combobox" aria-haspopup="true" aria-expanded="true" 
tabindex="-1" aria-disabled="false" aria-owns="select2-colourTypes-9c-results">
<ul class="select2-selection__rendered"><li class="select2-search select2-search--inline">
<input class="select2-search__field" 
type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" 
placeholder="" style="width: 0.75em;" aria-controls="select2-colourTypes-9c-results">
</li></ul></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>

</div>

我可能需要更清楚地了解您想要做什么,但从我从您的问题中收集到的信息来看,我认为您正在寻找一种方法来使用控制台填充所有这些字段,特别是这个选择字段。您应该能够简单地通过将其值设置为您想要选择的选项的值来填充它。

使用您包含的代码,下面的JavaScript将选择值为5的选项,即"Green":

document.querySelector('select[name="colourTypes[]"]').value = "5";
// selected  —>  <option value="5" data-select2-id="20">Green</option>

一旦运行这个,你甚至可以测试,以确保它实际上选择了这个选项在你的控制台中使用这些方法之一:

Array.from(document.querySelectorAll('select[name="colourTypes[]"] option')).filter(e => e.selected)[0].value;
// returns "5"
Array.from(document.querySelectorAll('select[name="colourTypes[]"] option')).filter(e => e.selected)[0].textContent;
// returns "Green"
document.querySelector('select[name="colourTypes[]"]').value;
// returns "5"

要对多个字段执行此操作,您可以对每个字段执行类似于此方法的操作,并连续运行它们。这是完成这项任务的一种方法。完成此任务的另一种方法(我的首选方法)是创建一个包含所有键/值(字段名/值)对的JavaScript对象,然后循环遍历该对象。这使得以后调整选择和附加字段更容易,而不必担心特定字段是哪种类型的字段。

让我们看看它在这里的作用:

const fieldValues = {
"Full Name": "David Webb",
"Alias": "Jason Bourne",
"Food": ["chicken","tacos"],
"Color": "#663399",
"DOB": "1970-09-13",
"Email": "thebourneybunch@gmail.com",
"Spam": "phone",
"Places": ["north-america","europe","antarctica"],
"State": "MO",
"Bio": "No, it doesn't start to come back. The knot's like everything else, I just found the rope and I did it.nnThe same way I can read, I can write, I can add, subtract, I can make coffee, I can shuffle cards, I can set up a chessboard.",
"Username": "JamesBondWishesHeWasMe",
"Password": "Kittens4EVER!"
};
const button = document.querySelector('button');
button.addEventListener('click', function() {
// loop through the `fieldValues` object we created to compare your desired values with those of the form fields
for ([fieldName, value] of Object.entries(fieldValues)) {
// store all found fields of each field name into a `fields` variable
const fields = Array.from(document.querySelectorAll(`[name="${fieldName}"]`));
// ensure that at least one field exists for each requested field name
if (fields.length) {
// if the input type permits multiple selected values (e.g. checkbox list, multi-select field)
if (fields[0].matches && (fields.length > 1 || (fields.length === 1 && fields[0].matches('select[multiple]')))) {
// store desired value as an array, even if it is a string, (i.e. "0" —> ["0"], ["1","2"] —> ["1","2"])
const values = [value].flat();
const isMultiSelect = fields[0].matches('select[multiple]');
// if the field is a multi-select field, evaluate its child option elements, otherwise, evaluate the actual fields (checkboxes)
const fieldOptions = isMultiSelect ? Array.from(fields[0].querySelectorAll('option')) : fields;
// deselect any pre-selected options for fields with the associated field name, using the selected/checked properties accordingly
fieldOptions.forEach(option => option[isMultiSelect ? "selected" : "checked"] = false);
// select/check any options/checkboxes that match values from the `fieldValues` object
fieldOptions.filter(option => values.includes(option.value)).forEach(option => option[isMultiSelect ? "selected" : "checked"] = true);
} else {
// if the field type only accepts one value, set it equal to the value from the `fieldValues` object
fields[0].value = value;
}
}
}
});
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css');
body {
padding: 30px;
}
form {
display: grid;
grid-template-columns: 120px 1fr;
gap: 10px;
}
label, input, textarea, select, button {
font-family: system-ui, arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
select[multiple] {
height: 130px;
overflow: hidden;
}
textarea {
height: 90px;
resize: none;
}
label, button {
font-weight: bold;
}
label + div {
display: flex;
flex-wrap: wrap;
gap: 5px 10px;
}
label + div > label {
white-space: nowrap;
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
appearance: none;
-webkit-appearance: none;
margin-bottom: 20px;
padding: 8px 16px;
background-color: #58f;
border: none;
border-radius: 50px;
font-size: 18px;
color: #fff;
cursor: pointer;
}
button i {
margin-left: 10px;
}
<button>Fill this form<i class="fas fa-magic"></i></button>
<form>
<label for="fullName">Full Name</label>
<input id="fullName" type="text" name="Full Name" placeholder="Clark Kent">
<label for="alias">Alias</label>
<input id="alias" type="text" name="Alias" placeholder="Superman (you get the idea…)">
<label for="favoiteColor">Favorite Color</label>
<input id="favoiteColor" type="color" name="Color" value="#FF0000">
<label for="food">I'm craving…</label>
<select id="food" name="Food" multiple>
<option value="chicken">Chicken</option>
<option value="fried-rice">Fried rice</option>
<option value="pizza">Pizza</option>
<option value="tacos">Tacos</option>
<option value="ice-cream">Ice cream</option>
<option value="pasta">Pasta</option>
</select>
<label for="dob">DOB</label>
<input id="dob" type="date" name="DOB">
<label for="email">Email Address</label>
<input id="email" type="email" name="Email">
<label for="spam">Spam me via…</label>
<div>
<label for="spam-email"><input id="spam-email" type="radio" name="Spam" value="email"> Email</label>
<label for="spam-phone"><input id="spam-phone" type="radio" name="Spam" value="phone"> Phone</label>
</div>
<label for="places">I've been to…</label>
<div>
<label for="africa"><input id="africa" type="checkbox" name="Places" value="africa"> Africa</label>
<label for="antarctica"><input id="antarctica" type="checkbox" name="Places" value="antarctica"> Antarctica</label>
<label for="asia"><input id="asia" type="checkbox" name="Places" value="asia"> Asia</label>
<label for="australia"><input id="australia" type="checkbox" name="Places" value="australia"> Australia</label>
<label for="europe"><input id="europe" type="checkbox" name="Places" value="europe"> Europe</label>
<label for="north-america"><input id="north-america" type="checkbox" name="Places" value="north-america"> North America</label>
<label for="south-america"><input id="south-america" type="checkbox" name="Places" value="south-america"> South America</label>
</div>
<label for="state">Home state</label>
<select id="state" name="State">
<option value="" style="display: none;" disabled="disabled" selected="selected">Choose a state…</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<label for="bio">Bio</label>
<textarea id="bio" name="Bio" placeholder="Tell us a bit about yourself…"></textarea>
<label for="username">Username</label>
<input id="username" type="text" name="Username">
<label for="password">Password</label>
<input id="password" type="password" name="Password">
</form>

编辑:2021年2月22日

好的,我知道你在这里想做什么,从多选择字段中选择多个值。我最初的脚本并没有考虑到复选框列表和多选择字段等字段类型的多个选择值,但是通过一个小小的调整,我们也可以添加对这两种字段类型的支持!请检查上面的代码片段,因为我现在已经更新了它以反映这一点。

本质上,我们检查这些字段类型中的任何一个,如果它们存在,我们从它们的字段中清除任何预设值,然后循环遍历您所需输入的数组(单个字符串将被转换为包含该字符串的长度为1的数组)并选择每个所需值。使用三元表达式,我通过查看select的选项标记后代并将selected属性设置为true/false而不是checked属性来解释多选择字段和复选框列表。

最新更新