2

Here is the code I've created for validating my form.

$(function () {
    $('#subbtn').click(function () {
        if ($('#course').val('x')) {
            $('#s1').show();
        }
        if ($('#sem').val('x')) {
            $('#s2').show();
        }
    });

HTML

<button id="subbtn" type="submit>Submit</button
<span id="$s1" style="display:none;">*</span>
<span id="$s2" style="display:none;">*</span>

#course and #sem are the ids of List boxes.
After leaving both blank and press button it works properly (both the star will display), but after selecting first listbox and leave the second one empty, and prss the button then it gives the same result (that is, shows the both stars instead of one) Please help, Thank you in advance

2
  • How does the form is being generated? Dynamically? Commented Apr 26, 2015 at 12:45
  • check my updated code: in html id whats the use of $ Commented Apr 26, 2015 at 12:48

2 Answers 2

1

Please try this

$(function () {
    $(document).on('click', '#subbtn', function () {
        if ($('#course').val() == '') {
            $('#s1').show();
        } else {
            $('#s1').hide();
		}
        if ($('#sem').val() == '') {
            $('#s2').show();
        } else {
            $('#s2').hide();
		}
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="course">
	<option value=""></option>
	<option value="be">B.E</option>
	<option value="mba">MBA</option>
	<option value="arts">Arts</option>
	<option value="finance">Finance</option>
</select>
<select id="sem">
	<option value=""></option>
	<option value="1">1St</option>
	<option value="2">2nd</option>
	<option value="3">3rd</option>
	<option value="4">4th</option>
</select>
<button id="subbtn" type="submit">Submit</button>
<span id="s1" style="display:none;">*</span>
<span id="s2" style="display:none;">*</span>

Sign up to request clarification or add additional context in comments.

Comments

1

The condition is incorrect, it should be

if ($('#course').val() == 'x') {...}

instead of

if($('#course').val('x')) {...}

The same for the second list, #sem.

1 Comment

Thank you. I've modified, but first time it works, but second time after selecting the first listbox, its not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.