RAHUL VP
RAHUL VP

Reputation: 59

how to make a field mandatory inside if else condition in jquery

i written a jquery code to show ,hide text box depends upon value. so now i want to make that text box mandatory when it appear.

the code am using is below.

document.getElementById('other').style.display = 'none';

$("#donate").change(function(){
    var selected = $(this).val();
    if(selected  == 'item') {
       document.getElementById('other').style.display = 'block';
     } else {
        document.getElementById('other').style.display = 'none';
     }
});

how to make it mandatory. please anyone help me out to do this

Upvotes: 0

Views: 912

Answers (3)

Vipul Upadhyay
Vipul Upadhyay

Reputation: 124

$("#donate").change(function(){

 if($("#other").is(":hidden")==false)
    {
        if($('#other').val()==""){
        alert("Field is required");
        return;
    }


 });

Upvotes: 3

Dani
Dani

Reputation: 925

make some changes in your code

document.getElementById('other').style.display = 'none';

$("#donate").change(function(){
    var selected = $(this).val();
    if(selected  == 'item') {
       document.getElementById('other').style.display = 'block';
       document.getElementById('other').getAttribute('required',true);
       or
document.getElementById('other').getAttribute('required','required');
     } else {
        document.getElementById('other').style.display = 'none';
document.getElementById('other').getAttribute('required',false);
     }
});

i Hope it will help you now

Upvotes: 0

Manoj
Manoj

Reputation: 5071

On submit button you can do as follows

var donate = $("#donate").val();
if(donate == 'item') {
   var item = $('#other').val();
   if(item == ''){
      alert('item is required.');
      return false;
   }
}

Upvotes: 0

Related Questions