Как отобразить сообщение проверки для радиокнопок со встроенными изображениями с помощью Bootstrap 4?

Опубликовано: 6 Января, 2022

По умолчанию Bootstrap 4 имеет различные функции формы для переключателей со встроенными изображениями. Здесь HTML 5 имеет функции проверки по умолчанию, однако для пользовательской проверки мы должны использовать JavaScript или jQuery. Следующие подходы помогут при отображении сообщения проверки для переключателей со встроенными изображениями.

Подход 1. Сначала оберните радиокнопки и их метку с помощью класса form-check-inline. Затем добавьте тег img в указанную выше оболочку после тега label. Используйте обязательную проверку по умолчанию, добавив обязательный атрибут радиокнопки. Наконец, отображайте сообщение с помощью класса предупреждений и запускайте его с помощью методов jQueries attr () , addClass () и html (), только если переключатель не установлен.

  • Пример: приведенная ниже программа иллюстрирует отображение сообщения проверки для переключателей с встроенными изображениями на основе описанного выше подхода.
    <!DOCTYPE html>
    < html lang = "en" >
    < head >
    < meta charset = "utf-8" >
    < meta name = "viewport" content =
    "width=device-width, initial-scale=1" >
    < link rel = "stylesheet" href =
    < script src =
    </ script >
    < script src =
    </ script >
    < script src =
    </ script >
    < style >
    body {
    text-align: center;
    }
    h1 {
    color: green;
    }
    </ style >
    </ head >
    < body >
    < div class = "container" >
    < h1 >GeeksforGeeeks</ h1 >
    < br >< br >
    < p >Selcet Your Gender</ p >
    < form >
    < div class = "form-check form-check-inline" >
    < input class = "form-check-input"
    type = "radio"
    name = "inlineRadioOptions"
    id = "inlineRadio2"
    value = "option2" required>
    < label class = "form-check-label"
    for = "inlineRadio2" >
    < img id = "option2img" src =
    class =
    "rounded-circle rounded-sm img-fluid img-thumbnail" >
    </ label >
    </ div >
    < div class = "form-check form-check-inline" >
    < input class = "form-check-input"
    type = "radio"
    name = "inlineRadioOptions"
    id = "inlineRadio3"
    value = "option3" required>
    < label class = "form-check-label"
    for = "inlineRadio3" >
    < img id = "option3img" src =
    class =
    "rounded-circle rounded-sm img-fluid img-thumbnail" >
    </ label >
    </ div >
    < br >
    < div class = "form-check form-check-inline" >
    < input type = "submit"
    class = "form-control mt-3 "
    value = "Submit"
    name = "submit"
    id = "checked" />
    </ div >
    </ form >
    < br >< br >
    < span id = "msg" ></ span >
    </ div >
    < script >
    // On clicking submit do following
    $("input[type=submit]").click(function() {
    var atLeastOneChecked = false;
    $("input[type=radio]").each(function() {
    // If radio button not checked
    // display alert message
    if ($(this).attr("checked") != "checked") {
    // Alert message by displaying
    // error message
    $("#msg").html(
    "< span class = 'alert alert-danger' id = 'error' >"
    + "Please Choose atleast one</ span >");
    }
    });
    });
    </ script >
    </ body >
    </ html >
  • Выход:

Подход 2. Оберните радиокнопки вместе с тегом img для встраивания, используя класс form-inline и input-group. Затем отобразите сообщение с помощью класса предупреждений и активируйте его с помощью методов jQuery attr () , addClass () и html (), только если переключатель не установлен. Наконец, получите проверенные значения с помощью функции jQuery val () и объедините ее с компонентом предупреждения Bootstrap, чтобы отобразить сообщение об успешной / неудачной отправке формы. Кроме того, используйте функцию preventDefault (), чтобы предотвратить сброс формы после отправки, потому что для отображения сообщения об успешной / неудачной отправке. Не забудьте добавить тег img в указанную выше оболочку после тега label.

Примечание: запустите этот код в более широком окне.

Пример. В приведенном ниже примере показано, как отображать сообщение проверки для переключателей с встроенными изображениями на основе описанного выше подхода.

<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1" >
< link rel = "stylesheet" href =
< script src =
</ script >
< script src =
</ script >
< script src =
</ script >
< style >
body {
text-align: center;
}
#option3img {
transform: rotate(270deg);
}
#option1img {
transform: rotate(180deg);
}
body {
margin: 55px;
}
input[type=submit] {
position: absolute;
left: 43%;
top: 52%;
}
h1 {
color: green;
}
</ style >
</ head >
< body >
< div class = "container" >
< h1 >GeeksforGeeeks</ h1 >
< br >
< p >< strong >
Choose the Correct logo for GeeksforGeeks
</ strong ></ p >
< form >
< div class = "form-inline" >
<!--form group with image inline-->
< div class = "input-group mr-sm-2" >
< div class = "form-check-inline" >
< label class = "form-check-label input-group-text ml-2" >
< input type = "radio" aria-label =
"Radio button for following text input"
name = "Radiobtn" id = "option1" value = "option1" >
< img id = "option1img"
src =
class =
"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2" >
</ label >
</ div >
</ div >
< div class = "input-group mr-sm-2" >
< div class = "form-check-inline" >
< label class = "form-check-label input-group-text " >
< input type = "radio"
aria-label = "Radio button for following text input"
name = "Radiobtn" id = "option2" value = "option2" >
< img id = "option2img"
src =
class =
"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2" >
</ label >
</ div >
</ div >
< div class = "input-group mr-sm-2" >
< div class = "input-group-prepend" >
< div class = "form-check-inline" >
< label class = "form-check-label input-group-text ml-2" >
< input type = "radio"
aria-label = "Radio button for following text input"
name = "Radiobtn" id = "option3" value = "option3" >
< img id = "option3img"
src =
class =
"bd-placeholder-img rounded-right rounded-sm img-fluid ml-2" >
</ label >
</ div >
</ div >
</ div >
</ div >
< div class = "form-inline mt-5" >
< input class = "form-control mr-3 btn btn-info"
type = "submit" value = "Submit" >
</ div >
</ form >
< div class = "mt-3" id = "msg" ></ div >
< div class = "mt-3" id = "ans" ></ div >
</ div >
< script >
// On clicking submit do following
$("input[type=submit]").click(function() {
var atLeastOneChecked = false;
// If radio button not checked
// display alert message
$("input[type=radio]").each(function() {
if ($(this).attr("checked") != "checked") {
// Alert message by displaying
// error message
$("#msg").html(
'< span class = "alert alert-danger alert-dismissible fade show" id = "alert1" >'+
'Make atleast one choice'+
' < button type = "button" class = "close" data-dismiss = "alert" aria-label = "Close" >'+
'< span aria-hidden = "true" >×</ span ></ button ></ span >');
} else {
$("#msg").html(
'< span class = "alert alert-success alert-dismissible fade show" id = "alert2" >'+
'Success Choise Made'+
'< button type = "button" class = "close" data-dismiss = "alert" aria-label = "Close" >'+
'< span aria-hidden = "true" >×</ span ></ button ></ span >');
}
});
});
</ script >
< script >
$(document).ready(function() {
// Validation message for empty choice submission
$("input[type='submit']").click(function() {
var radioValue = $("input[name='Radiobtn']:checked").val();
if (radioValue) {
$("#msg").html(
'< span class = "alert alert-success alert-dismissible fade show" id = "alert3" >'+
'Success..! You Made your Choise : < strong >' + radioValue +
'</ strong >< button type = "button" class = "close" data-dismiss = "alert" aria-label = "Close" >'+
'< span aria-hidden = "true" >×</ span ></ button ></ span >');
if (radioValue == 'option2') {
// Validation message for correct choice
$("#ans").html(
'< span class = "alert alert-success alert-dismissible fade show" id = "alert4" >'+
'You Have Made Correct Choise : < strong >' + radioValue +
'</ strong >< button type = "button" class = "close" data-dismiss = "alert" aria-label = "Close" >'+
'< span aria-hidden = "true" >×</ span ></ button ></ span >');
} else {
// Validation message for wrong choice
$("#ans").html(
'< span class = "alert alert-warning alert-dismissible fade show" id = "alert5" >'+
'Warning ..! You Have Made Wrong Choise : < strong >' + radioValue +
'</ strong >< button type = "button" class = "close" data-dismiss = "alert" aria-label = "Close" >'+
'< span aria-hidden = "true" >×</ span ></ button ></ span >');
}
}
});
});
// To avoid form reload after submission//
$("form").submit(function(e) {
e.preventDefault();
});
</ script >
</ body >