Reputation: 3570
How can I append the id
of a button to an input
value on button click?
Example input (buttons pressed):
#en
#de
#fr
#it
#es
Example output:
<input name="langs" value="en,de,fr,it,es,">
This is what I have, but it's not working:
$(".lang-btn").click(function() {
$(this).toggleClass("active");
$("input[name=languages]").val() += $(this).attr("id") . ",";
});
I would then like to be able to re-adjust the input
value, removing the id
, when the button is pressed again.
Upvotes: 0
Views: 53
Reputation: 104795
Close, .val()
takes the value as a param:
$(".lang-btn").click(function() {
$(this).toggleClass("active");
var id = this.id,
currentValue = $("input[name=languages]").val();
//Check for existing
if (currentValue.indexOf(id) > -1) {
//remove it
currentValue = currentValue.replace(id + ",", "");
$("input[name=languages]").val(currentValue);
} else {
$("input[name=languages]").val(currentValue + id + ",");
}
});
Working demo: http://jsfiddle.net/9L76d0sr/
Upvotes: 3
Reputation: 1
If you have radio buttons, you could see if there are checked or not: document.getElementById("X").checked = true;
Then you can append them as you want in your input field
Upvotes: 0