Add prefix to form field on submit(Using JS)
I have a simple form of salesforce(Using Web-To-Lead). I want to add a JS to it so that "Mr. " is added in beginni开发者_开发知识库ng of the field "Full Name" when the form is submitted.
And the updated value gets passed on.
I will appreciate if someone can just give me the JavaScript function.
Thanks in advance.
Like David, I would strongly recommend against doing it. Unless you allow the user to supply their title (and without constraining their choices), don't use one at all.
If you really, really, really want to do it, and do it client-side:
function addTitleOnSubmit(formId, fieldId) {
var form = document.getElementById(formId);
if (form.addEventListener) {
form.addEventListener("submit", handleSubmit, false);
}
else if (form.attachEvent) {
form.attachEvent("onsubmit", handleSubmit);
}
function handleSubmit() {
form.elements[fieldId].value = "Mr. " + form.elements[fieldId].value;
}
}
// Then hook it up wherever you do your init:
addTitleOnSubmit('theForm', 'fullName');
That looks up the form's DOM element by an id
attribute, then uses the form element's elements
collection to look up the field.
Off-topic: A lot of these things are much easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth out browser differences like the addEventListener
/ attachEvent
thing above and add a lot of useful utility functions.
For instance, using jQuery, the above looks like this:
$('#theForm').submit(function() {
var fullName = this.elements.fullName;
fullName.value = 'Mr. ' + fullName.value;
});
精彩评论