Reputation: 319
I have a form in which users can talk on a chatroom. My problem is that I have a gallery in which users can select pictures.
My question is how could a user click a html link and for that html link to input text into the input so when the user clicks the link which says cat
it inputs into the text field :cat
.
This is the form I have so far:
<form method="POST" action="chat.php">
<input type="text" name="message"></input>
<input type="submit" />
</form>
This is the gallery:
<a href="#"><img src="cat.jpg"/></a>
So again, the question is how I could insert text into the text box once the user clicks the image of the cat?
Thank you for anyone who spends time on helping me solve this issue.
Upvotes: 0
Views: 185
Reputation: 333
I'd use
$('a > img').click(function() {
var imgName = retrieveImgName($(this).attr('src'));
$('input[name="message"]').val(':' + imgName);
});
var retrieveImgName = function(imgPath) {
return imgPath.substring(0, imgPath.indexOf('.'));
};
Doing that you can extract the logic for retrieving the name based on the src
attribute of the img
.
So, if the logic changes for some reason, you can sobstitute it quite easily.
Upvotes: 2
Reputation: 2992
You can create a js function and then call it with the anchor to change the value attribute of the input. Input type text should not have a closing tag either.
function changeChatInput(value) {
document.getElementById('chatInput').value = value;
}
<form method="POST" action="chat.php">
<input type="text" name="message" id="chatInput" />
<input type="submit" />
</form>
<a href="javascript: changeChatInput(':cat');">
<img src="cat.jpg" />
</a>
Upvotes: 2
Reputation: 471
Here is a solution in JS (without jQuery): http://jsbin.com/doqedodezo/3/edit?html,js,output
The image triggers a JS function and passes the text which is supposed to be added to the input field. I added a id to the input to address it.
Upvotes: 2
Reputation: 1111
You can achieve your job by using this jQuery syntax.
<script type="text/javascript">
$('a > img').click(function(e){
e.preventDefault();
$('input[name="message"]').val(':cat');
});
</script>
Upvotes: 1
Reputation: 6763
If you're using jQuery you could do something like this:
$('a.cat').click(function()
{
$('input[name="message"]').val(':cat');
});
In this case you would need to update the link with the following:
<a class="cat" href="#"><img src="cat.jpg"/></a>
Upvotes: 3