如何在单击时将文本追加到输入字段

how to append text to an input field on click?

本文关键字:追加 输入 字段 文本 单击      更新时间:2023-09-26

我有一个图像,每次你点击它,我想把图像的name(或id)附加到一个输入字段,然后提交它(如果可能的话,自动)。

<?php
?>
<!DOCTYPE HTML>
<html>
<head>
  <title></title>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="jstophp.js"></script>
</head>
<body>
<a><img id="rar" src="images/5euro.jpg"></a> <br />
<a><img id="rar2" src="images/5euro.jpg"></a> <br />

<form action="form2.php" method="post">
    Name: <label><input id="inputF" type="text" name="name"></label><br>
    <input type="submit">
</form>
</body>
</html>

这是form2.php:

<?php
?>
<!DOCTYPE HTML>
<html>
<head>
  <title></title>
</head>
<body>
<?php
echo "this is the name ". $_POST['name']
?>
</body>
</html>

这是javascript:

var check = null;
var x = $('#inputF');
$(document).ready(function(){
    $('img').click(function(){
        //gets attribute id from image
        check = $(this).attr("id");
        //puts image name into input field value (doesnt work)
        x.val(x.val() + check);
        //checks variable `check`
        console.log(check);
    });
});

当我打印到控制台check打印正常,但当我实际提交表单它不工作。

Try

 $('img').click(function(){
    $('#inputF').val($('#inputF').val() +","+ this.id)
    $("input[type=submit]").trigger("click");
});

脚本运行正常。把你的img标签包含在下面的表单标签中

<html>
<head>
  <title></title>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="jstophp.js"></script>
</head>
<body>
<form action="form2.php" method="post">
<a><img id="rar" src="images/5euro.jpg"></a> <br />
<a><img id="rar2" src="images/5euro.jpg"></a> <br />
    Name: <label><input id="inputF" type="text" name="name"></label><br>
    <input type="submit">
</form>
</body>

将x的赋值移到click函数中,如下所示:

var check = null;
$(document).ready(function(){
    $('img').click(function(){
        var x = $('#inputF');
        //gets attribute id from image
        check = $(this).attr("id");
        //puts image name into input field value (doesnt work)
        x.val(x.val() + check);
        //checks variable `check`
        console.log(check);
    });
});

这里是jsfiddle - http://jsfiddle.net/DKL79/

和代码:

var $form = $('#formF');
var $input = $('#inputF', $form);
$('img').on('click', function(e) {
    $input.val(this.id);
    $form.submit();
});

 $('img').click(function(){
   var test=$(this).attr("src");
   $('#inputF').val($('#inputF').val() +","+test)
});