Satch3000
Satch3000

Reputation: 49432

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...

I am looking for something like this:

IF checkbox_A is Checked then

If input_A is empty then alert('input_A is Required')

else Add a class="continue" to the div below.

<button id="btn1">Continue</button>

Possible?

Upvotes: 0

Views: 2518

Answers (4)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196306

Maybe

if ( document.getElementById('checkbox_A').checked ){
  if (document.getElementById('input_A').value == ''){
    alert('input_A is Required')
  } else {
    $('#btn1').addClass('continue;);
  }
}

But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..

<input type="text" name="...." class="required" />

now when you want to validate the form you do

// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
  // get their names
  var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
  // inform the user
  alert('The fields \n\n' + fieldnames + '\n\n are required');
  // focus on the first empty one so the user can fill it..
  fail.first().focus();
}

Demo at http://jsfiddle.net/gaby/523wR/

Upvotes: 1

Sverker84
Sverker84

Reputation: 465

yes, it's possible:

$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');

if (checkBoxA.checked())
{
    if (textBoxA.val() == "")
    {
        $('#btn1').removeClass('continue');
        alert("No value entered");
        textBoxA.focus();
    }
    else {
        $('#btn1').addClass('continue');
    }
} else {
    $('#btn1').addClass('continue');
}
});

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205


$(document).ready(function() {
  if($("#yourCheckBoxId").is(":checked")) {
     if($("#yourInputId").val() == "") {
          alert("empty");
     } 
     else {
        $("button[id='btn1']").addClass("continue");
     }
  }
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337743

I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.

if ($("#checkboxA").is(":checked")) {
    if ($("#inputA").val() == "") {
        alert("input_A is required");
    }
    else {
        $("#btn1").addClass("continue");
    }
}

Upvotes: 2

Related Questions