I have an eCommerce website product page for a product with color options.
I'm trying to copy the selected color attribute value and append it to the product title, and I'm using any change to the value of #pa_finish as a trigger, to ensure the title is updated with the current selection.
Here is the code I'm presently using:
$( '#pa_finish' ).change(function(){
var var_name = $('#pa_finish :selected').text();
var original = $('h1.product_title.entry-title').text();
$('h1.product_title.entry-title').html(original + ' ' + var_name);
});
The issue I'm having is that, instead of the title refreshing with each trigger, the var_name variable is being iterated alongside the previous value, so the product title ends up simply increasing in length!
Ideally, the pre-existing text value from var_name is cleared, and replaced with the new selection each time a change is made.
Is there a means by which I can 'reset' the function each time it is triggered? Thank you in advance for any help or insight anyone might be able to provide.
Thank you all for your input - I've realised that, as pointed out in the comments, I hadn't established a baseline value for my title.
I have a working example now:
var title = $('h1.product_title.entry-title').text();
$( '#pa_finish' ).change(function() {
var var_name = $('#pa_finish :selected').text();
$('h1.product_title.entry-title').html(title + ' ' + var_name);
});
I've established a value for the original title in a 'title' variable (outside of the function), so that when the function executes it replaces the HTML of:
$('h1.product_title.entry-title')
...with a combination of the original title and the var_name variable, on each change.
Before, it was simply loading the selector again and again, and tagging on the result of var_name, which is why I saw the repitition.
I hope this can help someone in the future.