Change partial values in input box
could someone help me to figure out if it is possible to take part of the value entered into an input field and change the value. What I a开发者_开发技巧m trying to do is make sure that addresses are entered correctly. So if someone puts in:
111 Circleview Road it would be changed to 111 Circleview Rd.
This is what I am trying with but having no luck, so I don't know if I am doing this wrong or if this is not possible to do with jQuery
$("#address").blur(
function(){
switch ($(this).val()){
case 'Road':
case 'road':
$(this).replaceWith("Rd.");
break;
case 'Street':
case 'street':
$(this).replaceWith("St.")
default:
$(this).val();
break;
}
}
);
Just use regular expression to find the words - it's just string manipulation in JavaScript.
$("#myinput").blur(function(){
this.value = this.value
.replace(/[Rr]oad/g,'Rd.')
.replace(/[Ss]treet/g,'St.');
});
Example: http://jsfiddle.net/jonathon/4Yuym/
You don't need to use $(this).val()
on an input element since value
is part of the element's native properties - so you can use this.value
to get/set.
Use regualar expressions for that.
$(this).val( $(this).val().replace(/Road/, "Rd.") );
If someone enters 111 Circleview Road, $(this).val()
will return that entire string, not just 'Road' or 'Street'.
So, unfortunately I'm not sure that a switch statement will really work for you here.
You may need to use regular expressions instead to find and replace text.
replaceWith is not the function you are looking for. Try this:
var newValue = $(this).val().replace('Road', 'Rd.');
$(this).val(newValue);
EDIT Also, Brian's response is important too. As your code currently is structured, none of the case statements will execute. Get rid of it and just use this regex.
var newValue = $(this).val().replace(/road/gi, 'Rd.')
$(this).val(newValue)
精彩评论