Jquery: Append a Form Input Value (.val)
I am trying trying to write a s开发者_C百科tring of multiple values depending on whether specific checkboxes are checked. i.e.
$('#submit').click(function() {
if ($('#box1').attr('checked')) {
$('#MyInput').val('box1 ');
alert('1');
}
if ($('#box2').attr('checked')) {
$('#MyInput').val('box2 ');
alert('2');
}
});
The return I am looking for in this case would be '1 2', however only the second value is written in the input field.
The alerts tell me that both events in the argument are firing. Is there another method for appending values?
The .val()
does not append.. it sets the value to whatever you pass, overwriting the previous value.
$('#submit').click(function() {
var myInput = $('#MyInput').val('')[0];
if($('#box1').attr('checked')){
myInput.value += 'box1 ';
alert('1');
}
if($('#box2').attr('checked')){
myInput.value += 'box2 ';
alert('2');
}
else {}
});
And if you have multiple checkboxes that you want all of their values added to the myInput element if they are checked you can add a class to all of them and just do
$('#submit').click(function() {
var myInput = $('#MyInput').val('')[0];
$('.common-class-to-all:checked').each(function(){
myInput.value += this.value + ' ';
});
});
demo http://jsfiddle.net/SQcGq/
You're replacing the value of MyInput
each time. .val
does not add on to the value of the input field, it replaces it.
var value = [];
if ($('#box1').prop('checked')) {
value.push('box1');
}
if ($('#box2').prop('checked')) {
value.push('box2');
}
$("#MyInput").val(value.join(' '));
Give the boxes a class like boxes
, and use the map()
[docs] method to get a collection of the values, the get()
[docs] method to convert it to an Array, and .join()
to join them into a string.
Then set the resulting string once as the value using the val()
[docs] method.
$('#submit').click(function() {
var values = $('.boxes').map(function() {
return this.checked ? this.id : '';
}).get().join(' ');
$('#MyInput').val( values );
});
EDIT: The requirement was to use a string equal to the ID for the result. Fixed. Thanks to @Bryan for the heads up.
I suppose it's a typo? In the first if
you check the "checked" value, in the second if
you check for the "checked" attribute
In case you use jQuery 1.6+ you should use $('#box1').prop("checked")
Check/modify this demo: http://jsfiddle.net/roberkules/45WgD/
$('#submit').click(function() {
var values = [];
$("#box1, #box2").filter(":checked").each(function(i, box){
values.push($(box).attr("id"));
});
$('#MyInput').val(values.join(" "));
});
Doing $('#MyInput').val('box1 ');
overwrites the value of the textbox, which is why you're only seeing the second value, this should work:
$('#submit').click(function() {
var new_val = '';
if($('#box1').is(':checked')){
new_val += 'box1 ';
}
if($('#box2').is(':checked')){
new_val += 'box2 ';
}
$('#MyInput').val(new_val);
else {}
});
精彩评论