rochellecanale
rochellecanale

Reputation: 205

How to pass a jquery value in a div or form and assign it in a hidden textbox?

just want to ask a question about passing a value using jquery and assigning it in a form hidden textbox. Here's my code i hope you can help me.

**homepage.php**
 <?php
    $cat_id = $row['salescatid'];
 ?>
 <input type="button" name="add_comment" data-value="<?php echo $cat_id; ?>" value="Add Comment" class="comment" />
 .
 .
 <div id="comment_category">
 <!-- DISPLAY COMMENT HERE -->
 </div>
 <?php echo form_open('CATEGORY_CONTROLLER/INSERT_COMMENT'); ?>
 <div id="comment_add" style="display: none;">
    <input type="hidden" value="" name="cat_id" /> //Here's the problem how can i get the value from my jquery?
    <input type="hidden" value="sales_category" name="type"/>
    <label>Write your comment</label><br />
    <textarea name="comment_category" style="width: 50%; resize: none;"></textarea><br />
    <input type="submit" value="COMMENT" class="btn btn-primary btn-SMALL"/>
 </div>
 <?php echo form_close(); ?>
 .
 .
 .
 //Here's my jquery
 $(".comment").click(function(){
       var id = $(this).attr('data-value'); //This is the value of the button, problem is how to pass it in my comment form?
       $("#comment_add") .show();
       //alert(id);
 });

Please help me guys. Thanks.

Upvotes: 1

Views: 6978

Answers (3)

carl-lopez
carl-lopez

Reputation: 582

I'd suggest adding an id to the element so you can easily select it:

<input type="hidden" value="" id="cat_id" name="cat_id" />

Alternatively you can also select it by its name as suggested in other answers and then you can set its value easily with jQuery:

var id = $(this).attr('data-value');
$("#cat_id").val(id);

Hope this helps!

Upvotes: 0

Aguardientico
Aguardientico

Reputation: 7779

$('input[name="cat_id"]').val(id);

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .val() to assign a value to an input element and use attribute selector to select the input field using the name attribute

$('input[name="cat_id"]').val($(this).attr('data-value'))

Ex:

 $(".comment").click(function(){
       var id = $(this).attr('data-value'); //This is the value of the button, problem is how to pass it in my comment form?
       $('input[name="cat_id"]').val(id)
       $("#comment_add") .show();
       //alert(id);
 });

Upvotes: 3

Related Questions