Ash3317
Ash3317

Reputation: 41

Input field validated only for first input field and not able to remove input field

I had created Ul which add the student input field with value and user can remove the field as well,Initially I am comparing student field value with each input field which are created to avoid duplication but it works only for first input field value not for others I used loop as well but its not working and not able to remove one input field at a time.

Here is my fiddle code

$('#addBtn').click(function () {
     var studentArray = $(".students").text();
     var i=" " ;
        console.log(studentArray);
        var studentSplitResult = studentArray.split('Remove');
        console.log(studentSplitResult);
         for (var i = 0; i < studentSplitResult.length; i++) {
                  if ($("#selectStd").val() !== $(".students").val()) {
                    $(".stdList").show();
                    var input_value = $('#selectStd').val();

                    $('ul').append('<input class="students" value="' + input_value + '"><a href="" class="deleteStd">Remove</a></input>');
                    console.log($(".students").val());
                   // console.log(studentSplitResult[i]);

                };


            return false;
        }

});

//prevent default action
$(document).on('click', 'a', function (e) {
    e.preventDefault();
    $(this).parent().remove();
});

Upvotes: 0

Views: 78

Answers (6)

naveen namani
naveen namani

Reputation: 152

Hello first of all you need to get a good understanding of the DOM traversing, which can really help you to organise the students that you are adding to the list, and removing.

Here a simple solution can be implemented as follows. First encapsulate all the students in a div tag with 'students' class name, and in that div, place the student text field with 'stdname' class and the anchor tag to help in removing the student details.

Now when traverse through all the students with 'stdname' class and check if there is a duplicate value.

Here is the code please check out.

and check on jsfiddle too.http://jsfiddle.net/naveen_namani/842bf5ke/1/

$('#addBtn').click(function () {
	var student_list=document.querySelectorAll(".students .stdname");
  var selectStd=document.getElementById("selectStd");
  var duplicate=false;
  for(var i=0;i<student_list.length;i++) {
  	if(student_list[i].value==selectStd.value) duplicate=true;
  }
  if(duplicate==false) {
  	$('ul').append('<div class="students"><input value="'+selectStd.value+'" class="stdname"/><a href="" class="deleteStd">Remove</a>');
  }
  return false;
});
$(document).on('click', 'a', function (e) {
  e.preventDefault();
  $(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="width:422px;border:1px solid #00A4CC;">
  <div id="errorLabel"></div>
  <div id="parentType" >
    <form id="parentForm" name="parentForm">
      <table style="margin-left: 8px;">
        <tr>
          <th>Select Student</th>
          <td>
            <input class="form-control" id="selectStd" placeholder="Please select students">
          </td>
          <td>
             <button id="addBtn" class="btn btn-default" style="margin-left: 17px;" >Add</button>
          </td>
        </tr>
      </table>
      <ul class="stdList">
        <label>Selected Students:</label>
        <br><br>
      </ul>
      <table ></table>
    </form>
  </div>
</div>

Upvotes: 0

KarelG
KarelG

Reputation: 5244

I have encountered two issues: input validation itself (your question) and the removal of the element when you click on the anchor element.

For input validation, I have rewritten it a bit. What I did is

1. Obtain new student value
2. Check if not empty by if(newStudent). If it's empty, nothing happens
3. obtain other inputs
4. match the new input against the values inside other inputs
  4a. if match, don't add it.
  4b. if no match, add it

For removing the element, You need to revise your HTML. It's not so correct. I have wrapped it around with a <section> element to have a save removal and corrected the HTML use.

A side note, you may also reconsider this

$(document).on('click', 'a', function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

If your HTML page has multiple anchor (<a>) elements, this function is used too on another anchor elements. If you click on these, it will remove these from the page upon click. If you don't want it, please revise the above function.

$('#addBtn').click(function(e) {
  // obtain new student value
  var newStudent = $('#selectStd').val();
  
  // check if it is not empty
  if (newStudent) {
    // obtain other names and check if there is no match
    var studentArray = $(".students");
    var hasMatch = false;
    studentArray.each(function(i, el) {
      if (el.value === newStudent) {
        hasMatch = true;
        return; // stopping loop
      }
    });

    // if there is no match, add student
    if (!hasMatch) {
      $('ul.stdList').append('<section><input class="students" value="' + newStudent + '" /><a href="" class="deleteStd">Remove</a></section>');
    }
  }

  return false;
});

//prevent default action
$(document).on('click', 'a', function(e) {
  e.preventDefault();
  $(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="panel panel-body" style="    width:422px;border: 1px solid #00A4CC;">
  <div id="errorLabel"></div>

  <div id="parentType">
    <form id="parentForm" name="parentForm">
      <table style="margin-left: 8px;">
        <tr>
          <th>Select Student</th>
          <td>
            <input class="form-control" id="selectStd" placeholder="Please select students">
          </td>
          <td>
            <button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button>
          </td>
        </tr>
      </table>
      <ul class="stdList">
        <label>Selected Students:</label>
        <br>
        <br>
      </ul>
    </form>
  </div>
</div>

Upvotes: 1

Prashant Shirke
Prashant Shirke

Reputation: 1423

You can simplify your code like below.

Just check any text input has the new value before adding using filter. It will also handle case insensitivity (remove if required).

Also while removing consider the removing the text input only.

Added e.preventDefault() to restrict the form posting. change or remove it as per requirement.

$('#addBtn').click(function(e) {
  e.preventDefault();
  var input_value = $("#selectStd").val();


  var isValid = $('input.students').filter(function() {
    return this.value.toLowerCase() == input_value.toLowerCase();
  }).length <= 0;

  if (isValid) {
    $('ul').append('<input class="students" value="' + input_value + '"><a href="" class="deleteStd">Remove</a></input>');

  } else {
    alert('Duplicate');
  }


});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
  e.preventDefault();
  $(this).prev('.students').remove();
  $(this).remove();
});
<body>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>


  <div class="panel panel-body" style="    width:422px;border: 1px solid #00A4CC;">
    <div id="errorLabel"></div>



    <div id="parentType">
      <form id="parentForm" name="parentForm">
        <table style="margin-left: 8px;">
          <tr>
            <th>Select Student</th>
            <td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
            <td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
          </tr>
        </table>
        <ul class="stdList">
          <label>Selected Students:</label><br>
          <br>
        </ul>
        <table>


        </table>
      </form>






    </div>

  </div>



  </div>


</body>

Upvotes: 2

Md Junaid Alam
Md Junaid Alam

Reputation: 1349

You are trying to delete the parent element of anchor tag. Just update your code like this

 $('ul').append('<div><input class="students" value="' + input_value + '"><a href="" class="deleteStd">Remove</a></input></div>');

then clicking on anchor will delete the parent of anchor element.

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

So based on your requirements, try this below code:

  1. Student names can't be duplicate
  2. And on removing, all names shouldn't removed.
  3. While adding, code checks if the student name exists. If yes, it throws an error/alert.

$('#addBtn').click(function() {
  var valueToCheck = $("#selectStd").val();
  var flag = true;
  $(".students").each(function() {
    if ($(this).val() === valueToCheck) {
      flag = false;
    }
  });
  if (flag) {
    $('ul').append('<span class="addedStudent"><input class="students" value="' + valueToCheck + '" /><a href="" class="deleteStd">Remove</a></span>');
  } else {
    alert(valueToCheck + " already exists.");
  }
  return false;

});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
  e.preventDefault();
  $(this).parents(".addedStudent:first").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="    width:422px;border: 1px solid #00A4CC;">
  <div id="errorLabel"></div>
  <div id="parentType">
    <form id="parentForm" name="parentForm">
      <table style="margin-left: 8px;">
        <tr>
          <th>Select Student</th>
          <td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
          <td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
        </tr>
      </table>
      <ul class="stdList">
        <label>Selected Students:</label><br>
        <br>
      </ul>
      <table>
      </table>
    </form>
  </div>
</div>

Upvotes: 0

gkempkens
gkempkens

Reputation: 460

When adding you try this:

$('ul').append('<input class="students" value="' + input_value + '"><a href="" class="deleteStd">Remove</a></input>');

Unfortunately this will not result in what you expect. The anchor will be adding by your browser next to the input not nested. Like this:

<input class="students" value="thevalue" />
<a href class="deleteStd">Remove</a>

So if you do this afterwards for removing $(this).parent().remove(); you will remove the entire container.

What you need to do is this:

$('ul').append('<div><input class="students" value="' + input_value + '" /><a href="" class="deleteStd">Remove</a></div>');

This will work. I have updated your fiddle: https://jsfiddle.net/Lojdfyhn/1/

Upvotes: 0

Related Questions