Reputation: 147
I'm new to JQuery so this question might be an obvious one, but I have something that appends a text to what's already in an input box:
$('a.blog_category').click(function(){
var current_value = $('#id_category').val();
$('#id_category').val(current_value + ', '+ this.text);
return false
})
I'd like to add an if clause that sounds like:
"If there is already a comma at the end of the line, don't add a comma." "If there is not already a comma AND it's not the first item in the input text, add a comma."
I hope that makes sense.
Thanks for any help beforehand.
Upvotes: 1
Views: 168
Reputation: 66042
Here's an updated function with how I would accomplish this using regex's.
$('a.blog_category').click(function(){
var current_value = $('#id_category').val();
if (!current_value.match(/,$/) && !current_value.match(/^,/)) {
// no commas were found in the wrong places :)
$('#id_category').val(current_value + ', '+ this.text);
return false;
} else {
// commas were found...don't put a comma :(
$("#id_category").val(current_value + ' ' + this.text)
});
Upvotes: 1
Reputation: 10857
The simplest way is to just write the logic to check for all that you mentioned. There might be a cleaner way with selectors but I would have to spend more time thinking about that. But doing something like this should work:
$('a.blog_category').click(function(){
var current_value = $('#id_category').val();
if (current_value.charAt(current_value.length - 1) != "," && current_value.indexOf(",") > -1)
{
$('#id_category').val(current_value + ', '+ this.text);
}
else
{
$('#id_category').val(current_value + this.text);
}
return false
})
EDIT: Skip above. I think you are just looking for something like this so maybe this will work better. No logic really needed:
$('a.blog_category').click(function(){
var current_value = $('#id_category').val();
var parts = current_value.split(",");
parts.push(this.text);
if (parts[0] == "")
parts.splice(0,1);
$('#id_category').val(parts.join(","));
return false
})
Upvotes: 1
Reputation: 728
Try:
$('a.blog_category').click(function(){
var current_value = $('#id_category').val();
stringArray = current_value.split(","); if(stringArray.length>= 1) {
//Split the string into an array and check the number of items in array
if (current_value.charAt(current_value.length)!=","){
//Check what the last character in the string is - apply comma if needed
$('#id_category').val(current_value
+ ', '+ this.text);
} } return false })
Upvotes: 0
Reputation: 14747
not so sure if jQuery has a helper function for it, but you can achieve this using plain Javascript with the following:
if (current_value.charAt(current_value.length - 1) != ',') {
current_value = current_value + ',';
}
Upvotes: 1