user2901740
user2901740

Reputation: 1571

Check if the textfields is null in Jquery

Im trying to check if the textfields is null using jquery, but its not working, The textfields is dynamically created and has name quiztxtBox[], with bracket, indicating it is an array, and when a certain field is null the textfield will turn red,. but the problem is it is not working, hmmm Here is my codes

$("#quiztxtBox[]").each(function()
              {
                  if($("#quiztxtBox[]").val()=="")
                  {
                      $("#quiztxtBox[]").nextAll('span').html("Field needs filling");
                      $("#quiztxtBox[]").css({"background-color":"#f6d9d4"});

                  }
          });

EDIT
This is the html codes, the span part is not working, I wonder why, this is the html for dynamically creating textboxes..

<div id="QuestionTBDiv1" >
                                        <label>Question</label><br/>
                                        <input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
                                        <label>Answer</label><br/>
                                        <input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A">&nbsp;<input type="radio" class = "choiceA" name="correct_answer1" value="A">&nbsp;
                                        <input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B">&nbsp;<input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/>
                                        <input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C">&nbsp;<input type="radio" class = "choiceC" name="correct_answer1" value="C">&nbsp;
                                        <input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D">&nbsp;<input type="radio" class = "choiceD" name="correct_answer1" value="D"><br>
                                        <span name="errMchoice" class="errorMsg"></span>
                                        </div>  

Upvotes: 1

Views: 56

Answers (2)

ReNiSh AR
ReNiSh AR

Reputation: 2852

Try this:

change id to class that is, change id="#quiztxtBox[]" to class=".quiztxtBox" then,

$(".quiztxtBox").each(function()
{
    if($(this).val()=="")
    {
         $(this).nextAll('span').html("Field needs filling");
         $(this).css({"background-color":"#f6d9d4"});
    }
});

i think you need this:

check demo @ http://jsfiddle.net/renishar/S73gq/

Upvotes: 0

hsz
hsz

Reputation: 152206

Try with:

$("[name='quiztxtBox[]']").each(function(){
  if ($(this).is(':empty')) {
    $(this).nextAll('span').html("Field needs filling");
    $(this).css({"background-color":"#f6d9d4"});
  }
});

Upvotes: 1

Related Questions