[英]how to append text to an input field on click?
我有一張圖片,每次單擊它時,我都想將圖片的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
可以正常打印,但是當我實際提交表單時,它不起作用。
嘗試
$('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);
});
});
$('img').click(function(){
var test=$(this).attr("src");
$('#inputF').val($('#inputF').val() +","+test)
});
這是為此的jsfiddle- http://jsfiddle.net/DKL79/
和代碼:
var $form = $('#formF');
var $input = $('#inputF', $form);
$('img').on('click', function(e) {
$input.val(this.id);
$form.submit();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.