I ha开发者_如何转开发ve a form with multiple text areas.
<textarea name="datasetname_1" cols="40" rows="5" id="datasetname_1" class="validate[required] text-input"></textarea><br>
<textarea name="datasetname_2" cols="40" rows="5" id="datasetname_2" class="validate[required] text-input"></textarea><br>
<textarea name="datasetname_3" cols="40" rows="5" id="datasetname_3" class="validate[required] text-input"></textarea><br>
I would like to replace any text that contains commas with dashes. This should work for text that's typed directly in the text areas or text that is pasted over. The text should be replaced before the form is submitted. How can I accommplish this with jquery or javascript?
I have tried this
$("#formID").submit(function() {
$("textarea").each(function() {
($(this).val().replace(',','-'));
});
});
with no luck.
$(this).val().replace(',','-');
will fetch the value, replace one comma with a hyphen and then does nothing because you don't store the value into a variable.
Instead, you can use:
$(this).val('some value');
to actually set the value.- Use a regular expression to replace all occurences.
- (Properly indenting your code helps a lot in general.)
E.g.: http://jsfiddle.net/pimvdb/HsFbN/.
$("#formID").submit(function() {
$("textarea").each(function() {
$(this).val($(this).val().replace(/,/g, "-"));
});
});
It is arguable whether jQuery should be used for everything, but you can also omit it here:
$("#formID").submit(function() {
$("textarea").each(function() {
this.value = this.value.replace(/,/g, "-");
});
});
Could try this:
$("textarea").each(function(){
var text = $(this).val();
$(this).val($(text).replace(',','-'));
});
$(this).val().replace(',','-')
just gets the value and returns a string with the replaced text. It doesn't assign it anywhere, though. What you want is probably this:
// jQuery
$textarea = $(this); // just so we don't build a jQuery object twice
$textarea.val($textarea.val().replace(/,/g, "-"));
// vanilla JS
this.value = this.value.replace(/,/g, "-");
That said, if this is an important transformation, you also need to make sure whichever page is receiving that input checks and makes sure that the commas have been replaced. JS validation is well and good for cleaning things up before you submit, just make sure you have a fallback.
精彩评论