How to append text in a form using ajax/javascript?
I have a form. Let's called it myform.
Inside there are checkboxes, such as these two:
<input type='checkbox' name='power_convention[]' value='SOME VALUE #1' />
<input type='checkbox' n开发者_运维百科ame='power_evidence[]' value='SOME VALUE #2' />
At the end of the form, there's a textarea.
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
If power_convention is checked, I want it to immediately append the value of that checkbox into the comments
checkbox with the following structure:
<h3>SOME VALUE #1</h3><br />
Similarly, if power_evidence is clicked, I want it to do the same thing, but obviously after whatever came before it.
How would I go about doing this?
Thanks!
A jQuery solution:
$('input[type="checkbox"]').change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val(function(i, v) {
return v.replace(new RegExp(val), '');
});
}
});
DEMO
This only works if val
does not contain any special regular expressions characters. In this case you would have to escape them.
Update: Actually, you don't need a regular expression here, v.replace(val, '')
will be just fine (thanks @Pinkie);
An alternative to regular expressions would be to recreate the content of the textarea:
var $inputs = $('input[type="checkbox"]');
$inputs.change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val('');
$inputs.not(this).change();
}
});
DEMO 2
jQuery
$('input[name="power_convention[]"]').click(function() {
// assuming you only want the value if the checkbox is being ticked
// not when it's being unticked
if ($(this).is(":checked")) {
$('#elm1').val("<h3>" + this.value + "</h3><br />");
}
});
If you want them both to insert into the same textarea
(and they're the only fields on the page that begin with power_) then you can change the selector to use
jQuery's Attribute Starts With selector:
`$('input[name^="power_"]`
Demo on jsfiddle.
First, you will need to add an onClick event handler to your checkbox:
<input type='checkbox' onClick="someFunction(this)" name='power_convention[]' value='SOME VALUE #1' />
Then, up in the head section, in a script tag, put
someFunction(checkbox) {
document.getElementById("elm1").value += "<h3>" + checkbox.value + "</h3>";
}
Here's a jsfiddle
$('input:checkbox[name*=power_]').click(function(){
value = '<h3>' + $(this).val() + '</h3> <br />';
prevVal = $('#elm1').val();
$('#elm1').val(prevVal + value );
});
精彩评论