简体   繁体   中英

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

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>

use the val method

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

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

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

links:

对于所有表单元素,您需要使用.val()

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

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;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM