Problem:
I am trying to update an input field based off what image the user clicks on. At the moment, I have images with the caption of a first and last name. When the user clicks on the image the first and last name is inserted into an input field (the picture is also highlighted but this is just using CSS to give the impression it’s selected).
The user can select several images which insert multiple names into the input field. However I want to remove a name if the image becomes unselected.
$('#userImage').click(function(e) {
$(e.target).toggleClass('active');
var name = $(e.target).parent().find('figcaption').text().toLowerCase();
if($(e.target).hasClass('active')) {
if($('.username').val() == 0) {
$('.username').val(name);
} else {
if($('.username').val().indexOf(name) == -1) {
$('.username').val($('.username').val() + "," + name);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="userImage">
<figure class="image">
<img src="imgsrc">
<figcaption>Bob Smith</figcaption>
</figure>
<figure class="image">
<img src="imgsrc">
<figcaption>John Doe</figcaption>
</figure>
</div>
<input class="username" name="username">
The code checks to make sure the the image is selected first, if the box is empty it will insert the name, if it already has a value, it then checks to make sure the value isn’t repeated and inserts another name.
How could I remove just the name of the image that isn’t selected?
Solution:
I rewrote your code to the following:
let users = [];
$('#userImage').click(function(e) {
let user = $(e.target);
let input = $('.username');
let name = user.parent().find('figcaption').text().toLowerCase();
user.toggleClass('active');
if(user.hasClass('active')) {
users.push(name);
} else {
if(users.includes(name)) {
users.splice(users.indexOf(name), 1);
}
}
input.val(users.join(', '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="userImage">
<figure class="image">
<img src="imgsrc">
<figcaption>Bob Smith</figcaption>
</figure>
<figure class="image">
<img src="imgsrc">
<figcaption>John Doe</figcaption>
</figure>
</div>
<input class="username" name="username">