3

On submit of this JSP, users should be required to select something other than "Please Select." If a user selects "Please Select" and submits the form, it should alert the user with a popup that they should change the field.

<td class="normalTD" nowrap class="alignLeft" width="16%">
<form:select class="requiredAttr" path="detail[${loop.index}].cd" cssClass="fotnStyle" id="cd" >
<form:option value="">Please Select</form:option>
    <c:forEach var="list" items="${override.list}">
        <c:choose>
        <c:when test="${override.listne null}">
            <c:choose>
            <c:when test="${list.listCd eq detail.cd}">
                <c:set var="selectStatus" value="SELECTED" />
            </c:when>
            <c:otherwise>
                <c:set var="selectStatus" value="" />
            </c:otherwise>
            </c:choose>
        </c:when>
        </c:choose>
        <option value="${list.listCd}" ${selectStatus}>
        <c:out value="${list.desc}" />
        </option>
    </c:forEach>
</form:select>
</td>

I used the following jQuery snippet and it worked fine on alerting users that a textbox was not filled, but did not affect the dropdown.

function validate(){
    $(".requiredAttr").each(function(){
    if($(this).val().length < 1 || $(this).val() == ""){
        alert("Please fill in all the required fields.");
        $(this).focus();
        return false;

    }else{
        return true;
    }
    });
    return false;
}

This is the generated HTML.

<td class="normalTD" nowrap class="alignLeft" width="16%">
<select id="cd" name="detail[0].cd" class="fotnStyle" class="requiredAttr">
    <option value="">Please Select</option>         
    <option value="1" >A</option>
    <option value="2" >B</option>                                               
    <option value="3" >C</option>                                                   
    <option value="4" >D</option>                                               
</select>
</td>
Amber M
  • 177
  • 1
  • 6

2 Answers2

1

Simply get the selected index of drop down, if it zero then no value is selected

if($("#cd").prop('selectedIndex') === 0) {
    alert(...);
}

OR

if($("#cd")[0].selectedIndex === 0) {
    alert(...);
}

Related posts:


OR

you can get the value of selected option, if it is empty then alert for selecting a value.

if($("#cd").val() === "") {
    alert(...);
}

Related posts:

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
1

Your logic is correct but you don't need the length of the value. A simple check on the value equal to empty would do the job.

function validate()
{
    $(".requiredAttr").each(function(){
    if($.trim($(this).val()) == ""){
        alert("Please fill in all the required fields.");
        $(this).focus();
        return false;

    }else{
        return true;
    }
    });
    return false;
}

Example : https://jsfiddle.net/8p3ftmuh/3/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26