gandjyar
gandjyar

Reputation: 1203

Jquery - Append value to Paragraph

I have 4 groups of data that are tied to a click-bind event. I'm trying to add the value from a hidden field contained within each group to a paragraph later in the page, so that when the checkbox is clicked from one or more groups of data, the value from the hidden field displays within the paragraph area.

I'd also like to get it so that when the checkbox is unclicked, it removes the value from the paragraph, but for now I'm just trying to get the value to display when the checkbox is clicked.

Here's what I've tried:

This is the hidden field within the group of data that stores the value:

<input id="servicename_<?php echo $i;?>" name="servicename_<?php echo $i;?>"
type="hidden" value="<?php echo $service->PRODUCT;?>"></input>

This is the click-bind event:

$('input[id^=ckNow_]').each(function(){
    $(this).bind('click',function(){
      if($(this).prop('checked'))
        {

var servicename = '#servicename_'+$(this).attr('value').split("_");

ServiceName += servicename;

$('#lblServiceName').append($(ServiceName));

EDIT to add the checkbox that is within each group:

<input type="checkbox" id="ckNow_<?php echo $i;?>" name="ckNow[<?php echo $i;?>]">
</input>

And then the paragraph text:

<p id="lblServiceName">Service Name
<input type="hidden" id="servicename" value="0"></input>
</p>

What am I doing wrong and how can I fix it? All responses are very appreciated and I'm completely open to any and all suggestions. Thank you.

Upvotes: 2

Views: 530

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

<p id="lblServiceName">Service Name
    <span></span>
    <input type="hidden" id="servicename" value="0"></input>
</p>

then

jQuery(function ($) {
    var $checks = $('.group-data input[name^="ckNow["]').change(function () {
        var vals = $checks.filter(':checked').map(function () {
            return $(this).closest('.group-data').find('input[id^=servicename_]').val()
        }).get();
        $('#lblServiceName span').text(vals.join(', '))
    })
})

Demo: Fiddle

Upvotes: 2

Related Questions