Reputation: 29
I have an image and everytime you click on it I want to append the name
(or id
) of the image into an input field and then submit it (automatically if possible).
<?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>
this is form2.php:
<?php
?>
<!DOCTYPE HTML>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "this is the name ". $_POST['name']
?>
</body>
</html>
this is the 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);
});
});
When I print into the console check
prints normally but when I actually submit the form it doesn't work.
Upvotes: 0
Views: 495
Reputation: 9
$('img').click(function(){
var test=$(this).attr("src");
$('#inputF').val($('#inputF').val() +","+test)
});
Upvotes: 0
Reputation: 25527
Try
$('img').click(function(){
$('#inputF').val($('#inputF').val() +","+ this.id)
$("input[type=submit]").trigger("click");
});
Upvotes: 1
Reputation: 2122
Here is jsfiddle for that - http://jsfiddle.net/DKL79/
and code:
var $form = $('#formF');
var $input = $('#inputF', $form);
$('img').on('click', function(e) {
$input.val(this.id);
$form.submit();
});
Upvotes: 0
Reputation: 1026
Move the assignment of x into the click function like this:
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);
});
});
Upvotes: 0
Reputation: 5211
Script is working fine. Include your img tag inside form tag like below.
<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>
Upvotes: 0