Validação de caixa de seleção múltipla em JavaScript
// HTML
/*
<div class="p-2">
<form onsubmit="return handleData()" method="post" action="https://postman-echo.com/post">
Select all the scripting languages you know:
<div style="visibility:hidden; color:red; " id="chk_option_error">
Please select at least one option.
</div>
<div>
<input type="checkbox" name="langs[]" id="langs_javascript" value="JavaScript" checked> <label for="langs_javascript">JavaScript</label>
</div>
<div>
<input type="checkbox" name="langs[]" id="langs_perl" value="Perl"> <label for="langs_perl">Perl</label>
</div>
<div>
<input type="checkbox" name="langs[]" id="langs_php" value="PHP" checked> <label for="langs_php">PHP</label>
</div>
<div>
<input type="checkbox" name="langs[]" id="langs_ruby" value="Ruby"> <label for="langs_ruby">Ruby</label>
</div>
<div>
<input type="submit" name="submit" value="Submit"/>
</div>
</form>
</div>
*/
// Javascript
function handleData()
{
var form_data = new FormData(document.querySelector("form"));
if(!form_data.has("langs[]"))
{
document.getElementById("chk_option_error").style.visibility = "visible";
return false;
}
else
{
document.getElementById("chk_option_error").style.visibility = "hidden";
return true;
}
}
Himanshu Jangid