How can I set the value of a hidden input field using Jquery?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 02:54:21

问题


I am attempting to set the value of a hidden input field to the same as the value of a clicked link.

This is what I have attempted which doesnt work:

$(document).ready(function(){
$(".delete_link").click(function(){
        var deleteID = $(this).attr("data-value"); 
        $("#delete_value").attr("value") = deleteID;
    });
});

The variable deleteID is correctly set.

and the form for reference:

<form name="delete_form" action="delete_post.php" method="POST">
    <p>Please confirm you want to delete this post.</p>
    <input type="submit" id="delete_submit" name="delete_submit" value="confirm" />
    <input type="hidden" id="delete_value" value="" />
</form>

回答1:


use the val method

$("#delete_value").val(deleteID);

also for data attributes you might want to use the data method

$(this).data('value');

links:

  • http://api.jquery.com/val/
  • http://api.jquery.com/data/



回答2:


For all form elements you need to use .val():

$("#delete_value").val(deleteID);



回答3:


A complete example you (http://jsfiddle.net/79HEY/):

HTML

<form id="deleteform" action="delete_post.php" method="POST">
    <p>Please confirm you want to delete this post.</p>
    <input type="submit" data-id="100" id="delete_submit" name="delete_submit" value="confirm" />
    <input type="hidden" id="delete_value" value="" />
</form>

JavaScript

$(document).ready(function(){
    $("#deleteform").submit(function(){
        var deleteID = $("#delete_submit").data("id");
        $("#delete_value").val(deleteID);
        return true;
    });
});


来源:https://stackoverflow.com/questions/16240993/how-can-i-set-the-value-of-a-hidden-input-field-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!