Adding values from a list of checkboxes to a textbox
I am new to jQuery, so I am not familliar with syntax of it.
The problem I am facing right now is, I have a dropdown list with some values and corresponding checkboxes. When someone selects a particular value from the dropdown i.e checks a checkbox from dropdown, I want to add the 'value' of the checkbox to the textbox which is besides the dropdown of checkboxes.
The code I have come up with is
$(".productr-dropdown li input[type='checkbox']").click(function(e){
var cmd = $(this).val();
addToTextBox(cmd);
});
function addToTextBox(cmd){
command = $(".z:eq(2)").find("#platform_Command").val();
if (command.indexOf(' '+cmd+' ')>=0)
return;
else {
// THIS IS THE NEXT PART WHERE I AM STUCK
// I don't know how to add/replace the contents of 'cmd'
// to the contents of 'command'(which is the value of the textbox)
}
}
开发者_如何学Python
To better explain my problem I will write a use case here, The user checks a checkbox from the dropdown, e.g the value of the checkbox checked is 'abc', the textbox in which I want to add this 'abc' already has a value say 'xyz hijkl defg'. what should happen is the value'abc' should get added to the textbox in such a way that the value of the textbox would be'xyz abc hijkl defg'
The problem I have is I am not sure whether I am invoking the correct event also.
One more approach I have in mind is, $(document).click(function(e) { $(".productr-dropdown").hide(); $(".productr-dropdown").each(["input='checkbox':checked"], function (e){ addToTextBox($(this).val()); }); });
Which one is better ?
What is the syntax to only select values in the dropdown which are checked ?
A HTML from you would be kind. I improvized here:
JSFIDDLE demo
I'm still not clear about what are you trying to achieve btw.
can't you do something like so:
$('#myTxt').val( $('#mytxt').val() + cmd )
?
You will want to rewrite from
command = $(".z:eq(2)").find("#platform_Command").val();
to
command = $(".z:eq(2)").find("#platform_Command");
and from
if (command.indexOf(' 'cmd+' ')>=0)
to
if (command.val().indexOf(' 'cmd+' ')>=0)
so that you can easily just use the following to adjust the value
command.val(command.val() + " " + cmd);
精彩评论