HTML5 required attribute one of two fields

前端 未结 4 1747
刺人心
刺人心 2021-02-05 03:26

I have a form with two required input fields:

4条回答
  •  猫巷女王i
    2021-02-05 03:48

    Based on Andy's answer, but I needed a checkbox implementation & came up with this.

    what role(s) do you want?
    
    
    
    
    where will you work?
    
    
    
    
    jQuery(function ($) {
        // get anything with the data-manyselect
        // you don't even have to name your group if only one group
        var $group = $("[data-manyselect]");
    
        $group.on('input', function () {
            var group = $(this).data('manyselect');
            // set required property of other inputs in group to false
            var allInGroup = $('*[data-manyselect="'+group+'"]');
            // Set the required property of the other input to false if this input is not empty.
            var oneSet = true;
            $(allInGroup).each(function(){
                if ($(this).prop('checked'))
                    oneSet = false;
            });
            $(allInGroup).prop('required', oneSet)
        });
    });
    

    Here for anyone else getting here by googling and wanting a quick solution for one of many checkboxes.

提交回复
热议问题