Reputation: 11296
On first submission, no option in the <select> is selected, causing HTML5 validation to fail, preventing submission altogether.
However, if we then select an option via JavaScript, submission still fails on subsequent submission.
It succeeds if you manually select an option other than the ones already selected (or if you deselect and reselect them).
Bug or feature? Is it already known behavior or documented somewhere? I couldn't find any references.
var done = false;
$(document).ready(function() {
$("#s").on("click", function() {
if (done) {
return;
}
// run once
done = true;
setTimeout(function() {
$("#a").prop("selected", true);
console.log($("#x").val());
}, 100); // delay to prevent submission with set option
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<select id="x" name="x" required="required" multiple="multiple">
<option value="a" id="a">Anton</option>
<option value="b">Berta</option>
</select>
<input id="s" type="submit" name="btn" value="Submit" />
</form>
Upvotes: 2
Views: 589
Reputation: 1871
It seems it has to do with setting .prop
on the <option>
.
When you set the selectedIndex
on the select
input, it all works. Check the updated fiddle:
document.getElementById('btn-select').addEventListener('click', function() {
var select = $("#x")[0];
// select the first one
// select.selectedIndex = 0;
// or loop through options and select based on a condition
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value === 'b') {
select.selectedIndex = i;
return;
}
}
})
https://jsfiddle.net/5hbey7en/8/
So your example would become:
var done = false;
$(document).ready(function() {
$("#s").on("click", function() {
if (done) {
return;
}
// run once
done = true;
setTimeout(function() {
$("#x")[0].selectedIndex = 0;
console.log($("#x").val());
}, 100); // delay to prevent submission with set option
});
});
Upvotes: 1