March 12, 2012

Jquery: Append/Remove items on hidden field on click

Question by user1056998

I have a program that allows you to record absence when a grid is clicked 1 time. When you click it the second time, it will record the grid as late. When you click it for the third time, the status will revert to the original. I am able to append absences to a hidden field to be posted on another php. However, I can’t seem to append the late records to another hidden field. When I look at my other php file, the absence is still recorded even if it should have been removed from the list. Worst part is, nothing is being appended to the late hidden field.

I badly need help with this. Also, I hope you could explain where I made a fault so I could understand the code. Thanks!

Here’s the code: http://jsfiddle.net/Ms6FP/2/

Answer by Magneon

A better way to do this would be to create the contents of the hidden fields on submit.

Assuming your submit button is given the id mySubmitButton and you have a hidden field with an id lateHiddenField, you can do something like:

$("#mySubmitButton").submit(function(){
  $(".late").each(function(index,value){  //iterate through each late student
    //append the late student's name
    $("#lateHiddenField").text($("#lateHiddenField").text()+value.text()+"n");
  })

  //do the same for the absent students
}

The advantages are:

  • Faster processing- this only runs once
  • Simpler code- you don’t have
    to revise anything

Answer by Starx

I am guessing you are trying to give out the total number of students who are late through different state of clicks.

On that case here is an working solution

Slight change to markup, to make it more manipulative

<div id="collect1">
    late: <span>0</span>
</div>

Then, count the length of your already maintained array and update

$("#collect1").children("span").html(late.length);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!