问题
I have an issue that I'm trying to solve. Need some advice to the right direction:
With Prestashop when creating combinations, you have a dropdwon-list on product page where customer can choose the combination from. Here within the product.tpl file I have created some extra button to get customers attention for a certain combination. Now I would like this combination beeing automatically selected and activated when user clicks on that button. I have inputted some javascript code within the product.tpl file which is also hiding some other elements when button is clicked. I just dont get it to work that a certain attribute option is selected on mouseclick. Someone may have some clue to solve this??
This is the select option list of the attributes within product page. For example I want on button click choose option "Large" and beeing activated within product page via onclick function with help of jquery/javascript within the template. How to achieve this?
<select id="group_4" class="attribute_select selectBox" onchange="findCombination();getProductAttribute();$('#wrapResetImages').show('slow');;" name="group_4" style="display: none;">
<option title="Small" selected="selected" value="21">Small</option>
<option title="Medium" value="41">Medium</option>
<option title="Large" value="40">Large</option>
<option title="Extralarge" value="25">Extralarge</option>
I have tried with this but it doesn't work:
$('#group_4 option[value='58']').attr('selected', 'selected').change();
回答1:
Your quotes are wrong, looking at the console you would get the error Uncaught SyntaxError: Unexpected number
$('#group_4 option[value='58']').attr('selected', 'selected').change();
^ ^
should be
$('#group_4 option[value="58"]').attr('selected', 'selected').change();
回答2:
To change the selected option, you can simply change the value of the select element using plain JS:
document.getElementById('group_4').value = 58;
You'd still need to trigger the change event after that, though.
See a simple example here: http://jsfiddle.net/BgBGL/1/ (uses alert as onchange callback)
来源:https://stackoverflow.com/questions/22721515/how-to-change-selected-attribute-via-javascript