JavaScript to change a multi level <select> into accordion - javascript

in my item post page, their is an for selecting main category and than after selecting it shows relevant sub category.
i want to change this in to a accordion. please help me how to change this. so when a user come to my website and try to post ad he should be shown accordion for selecting the main category and sub category. please help me to achieve this by modify the code or using java-script to achieve this.
the code `
$categoryID = Params::getParam('catId');
if( osc_item_category_id() != null ) {
$categoryID = osc_item_category_id();
}
if( Session::newInstance()->_getForm('catId') != '' ) {
$categoryID = Session::newInstance()->_getForm('catId');
}
$subcategoryID = '';
if( !Category::newInstance()->isRoot($categoryID) ) {
$subcategoryID = $categoryID;
$category = Category::newInstance()->findRootCategory($categoryID);
$categoryID = $category['pk_i_id'];
}
if($categories == null) {
if(View::newInstance()->_exists('categories')) {
$categories = View::newInstance()->_get('categories');
} else {
$categories = osc_get_categories();
}
}
if ($item == null) { $item = osc_item(); }
$subcategory = array();
?>
<select id="parentCategory" name="parentCatId">
<option value=""><?php _e('Select a category', 'modern'); ?></option>
<?php foreach($categories as $_category) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $_category['pk_i_id']) || (isset($categoryID) && $categoryID == $_category['pk_i_id']) );
if($selected) { $subcategory = $_category; };
echo '<option value="'.$_category['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$_category['s_name'].'</option>';
} ?>
</select>
<select id="catId" name="catId">
<?php
if(!empty($subcategory)) {
if( count($subcategory['categories']) > 0 ) {
echo '<option value="">'.__('Select Subcategory', 'modern').'</option>';
foreach($subcategory['categories'] as $c) {
$selected = ( (isset($item["fk_i_category_id"]) && $item["fk_i_category_id"] == $c['pk_i_id']) || (isset($subcategoryID) && $subcategoryID == $c['pk_i_id']) );
echo '<option value="'.$c['pk_i_id'].'" '.($selected ? 'selected="selected"' : '' ).'>'.$c['s_name'].'</option>';
}
} else {
echo '<option value="'.$categoryID.'" >'._e('No Subcategory', 'modern').'</option>';
}
} else {
echo '<option value="">'._e('Select Subcategory', 'modern').'</option>';
}
?>
</select>
<script type="text/javascript" charset="utf-8">
<?php
foreach($categories as $c) {
if( count($c['categories']) > 0 ) {
$subcategory = array();
for($i = 0; $i < count($c['categories']); $i ) {
$subcategory[] = array($c['categories'][$i]['pk_i_id'], $c['categories'][$i]['s_name']);
}
printf('var categories_%1$s = %2$s;', $c['pk_i_id'], json_encode($subcategory));
echo PHP_EOL;
}
}
?>
$(document).ready(function(){
$("#parentCategory").bind('change', function(){
var categoryID = $(this).val();
if( categoryID == 0 ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
}
categories = window['categories_' categoryID];
if( categories==null || !$.isArray(categories) ) {
var options = '<option value="' categoryID '" selected=""><?php _e('No Subcategory', 'modern'); ?></option>';
} else {
var options = '<option value="' categoryID '" selected=""><?php _e('Select Subcategory', 'modern'); ?>...</option>';
$.each(categories, function(index, value){
options = '<option value="' value[0] '">' value[1] '</option>';
});
};
$('#catId').html(options);
$("#catId").next("a").find(".select-box-label").text('Select a Sub Category...');
$("#catId").change();
$("div#uniform-catId.selector").css('visibility', 'visible');
});
// In case of error and Category already chosen, let's show the Subcategory selector
if($("div#uniform-parentCategory.selector select").val()) {
$("div#uniform-catId.selector").css('visibility', 'visible');
}
});
</script>
<?php
}
?>`

If this is related to osclass, in item-post.php from bender (for example), use
<?php ItemForm::category_select(null, null, __('Select a category', 'bender')); ?>
instead of
<?php ItemForm::category_multiple_selects(); ?>
PS. This is not a js solution.

Related

Woocommerce Variations Radio buttons

I had the hooks below that's working perfectly to change the Products variations select to radio buttons while creating variations using custom attributes.
I added new products variations using the Global Attributes but it seems that the hook is not compatible with it.
am looking for a way to make it compatible with both since I already have 200 products using the custom attributes and want to start using global attributes for the new products.
function variation_radio_buttons($html, $args)
{
$args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args) , array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __('Choose an option', 'woocommerce') ,
));
if (false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product)
{
$selected_key = 'attribute_' . sanitize_title($args['attribute']);
$args['selected'] = isset($_REQUEST[$selected_key]) ? wc_clean(wp_unslash($_REQUEST[$selected_key])) : $args['product']->get_variation_default_attribute($args['attribute']);
}
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title($attribute);
$id = $args['id'] ? $args['id'] : sanitize_title($attribute);
$class = $args['class'];
$show_option_none = (bool)$args['show_option_none'];
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __('Choose an option', 'woocommerce');
$label = wc_attribute_label($args['attribute'], $args['product']);
if (empty($options) && !empty($product) && !empty($attribute))
{
$attributes = $product->get_variation_attributes();
$options = $attributes[$attribute];
}
$html = '<select id="' . esc_attr($id) . '" class="d-none ' . esc_attr($class) . '" name="' . esc_attr($name) . '" data-attribute_name="attribute_' . esc_attr(sanitize_title($attribute)) . '" data-show_option_none="' . ($show_option_none ? 'yes' : 'no') . '">';
$html .= '<option value="">' . esc_html($show_option_none_text) . '</option>';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all'
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options))
{
$html .= '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']) , $term->slug, false) . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</option>';
}
}
}
else
{
foreach ($options as $option)
{
// This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
//$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
//if (sanitize_title($option) == $current){
//$selected = 'selected';
//}
$selected = '';
$html .= '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>';
}
}
}
$html .= '</select>';
$radios = '<div class="radio-group">';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all',
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options, true))
{
$radios .= '<input id="' . strtolower($option) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($term->slug) . '" onClick="jQuery("#' . esc_attr($name) . '").val(' . esc_attr($term->slug) . ').trigger("change");" ' . checked(sanitize_title($args['selected']) , $term->slug, false) . '><label for="' . esc_attr($term->slug) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</label>';
}
}
}
else
{
foreach ($options as $option)
{
// $checked = sanitize_title($args['selected']) === $args['selected'] ? checked($args['selected'], sanitize_title($option), false) : checked($args['selected'], $option, false);
//if (sanitize_title($option) == $current){
//$checked = 'checked="checked"';
//}
$checked = '';
$radios .= '<input id="' . strtolower(sanitize_title($option)) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($option) . '" id="' . sanitize_title($option) . '" onClick="changeTrigger(\'#' . strtolower($attribute) . '\',\'' . esc_attr($option) . '\',\'' . esc_attr($label) . '\');" ' . $checked . '><label for="' . sanitize_title($option) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</label>';
$allAttribute[] = strtolower($attribute);
}
}
}
$radios .= '</div>';
return $html . $radios;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_radio_buttons', 20, 2);
function variation_check($active, $variation)
{
if (!$variation->is_in_stock() && !$variation->backorders_allowed())
{
return false;
}
return $active;
}
add_filter('woocommerce_variation_is_active', 'variation_check', 10, 2);
if (!function_exists('shop_attributes_in_loop'))
{
function shop_attributes_in_loop()
{
global $product;
//Getting product attributes
$product_attributes = $product->get_attributes();
if (!empty($product_attributes))
{
//Getting product attributes slugs
$product_attribute_slugs = array_keys($product_attributes);
?>
<script>
function resetAttr(c,d){
var attr = c;
jQuery('input[name=attribute_'+c+']').attr('disabled',false);
jQuery('input[name=attribute_'+c+']').attr('checked',false);
jQuery('#' + c + '-selected').html('');
jQuery('#' + c + '-section').removeClass('d-none');
jQuery('#' + c + ' option[value=""]').prop('selected', true);
if(d){
jQuery('#' + c).trigger('change');
}
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
jQuery(this).attr('disabled', false);
}
});
<?php
}
?>
}
function changeTrigger(a,b,c){
a = a.replace(/\s+/g, "-");
jQuery(a + ' option[value="' + b + '"]').prop('selected', true);
jQuery(a + '-selected').html('<div class="selected-variable"><span>'+c.replace(/#/, "").toUpperCase()+': '+b+' </span><a class="var-del" onClick="resetAttr(\''+a.replace(/#/, "")+'\',true)"><div class="close-x"></div></a></div>');
jQuery(a + '-section').addClass('d-none');
jQuery('input[name=attribute_'+a.replace(/#/, "")+']').attr('disabled',true);
jQuery(a).trigger('change');
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
resetAttr('<?php echo $attribute_name; ?>',false);
/*jQuery('input[name=attribute_<?php echo $attribute_name; ?>]').attr('checked',false);*/
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
//jQuery(this).attr('disabled', false);
}
});
<?php
}
echo "}</script>";
}
}
}
add_action('woocommerce_before_add_to_cart_button', 'shop_attributes_in_loop');

How do I change the value of all drop down menus to the option that is selected?

I am having difficulty figuring out a JavaScript function. I would like for all drop down menus below the selected value to change to that value.
Here is an example of what I want the drop down menus to do:
If I change the value of id 3 in Primer Source to "To Be Saved", then I want all the other drop down menus to change to that value.
I believe I will need a JavaScript function so I made one called changeNote which is called in the onChange of my <select> tag.
Here is my table:
<input type="hidden" id="primerSource_s<?=$i;?>" name="primerSource_s[<?=$i;?>]" value="<?=$abbNotes?>" class="primerSource" />
<select name="primerSource<?php echo $SampleID; ?>" id="primerSource<?php echo $SampleID; ?>" <?php echo $CSS_display0; ?> value onChange='changeNote(this);' >
<option value="" >Please Select</option>
<option value="Premixed"
<?php
if ("Premixed" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("Premixed" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>Premixed
</option>
<option value="To Be Saved"
<?php
if ("To Be Saved" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("To Be Saved" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>To Be Saved
</option>
<option value="Providing Primer"
<?php
if ("Providing Primer" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("Providing Primer" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>Providing Primer
</option>
<option value="Saved Primer(Eton)"
<?php
if ("Saved Primer(Eton)" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("Saved Primer(Eton)" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>Saved Primer(Eton)
</option>
<option value="Eton Universal Primer"
<?php
if ("Eton Universal Primer" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("Eton Universal Primer" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>Eton Universal Primer
</option>
<option value="To Be Synthesized By Eton"
<?php
if ("To Be Synthesized By Eton" == $_POST['primerSource' . $SampleID]) {
echo " selected = 'selected' ";
} elseif (($_POST['primerSource' . $SampleID] == '') && ("To Be Synthesized By Eton" == $abbNotes)) {
echo " selected = 'selected' ";}
?>
>To Be Synthesized By Eton
</option>
</select>
I made this changeNote function, but I went through code from other parts of the website that did what I was asking for. I am not sure why it is not working.
function changeNote(myselectbox){
var value = myselectbox.value;
var elements = document.querySelectorAll('.SampleName');
var index = parseInt(myselectbox.id.match(/\d+$/));
var filled_rows = 0;
for( var a = 0, l = elements.length; a < l; a++ ) {
if( document.getElementById('.SampleName'+a).value != "") {
filled_rows++
console.log(`filled rows: ${filled_rows}`)
}
}
if(value=="Synthesize"){
$("#check_space"+index).css("display","block");
$("#hasOligo"+index).attr("value",true);
$("#hasOligo"+index).attr("checked",true);
$("#hasOligo_"+index).attr("value",true);
$("#PrimerCntr"+index).attr("value","");
$("#PrimerCntr_t"+index).attr("value","");
$("#PrimerCntr_t"+index).prop("disabled",true);
$("#GlobalPrimerCntr"+index).val("");
$("#GlobalPrimerCntr"+index).prop("disabled",true);
$("#Notes_s"+index).val("Synthesize");
$("#Notes"+index).attr("value","Synthesize");
$("#Notes_s"+index).prop("disabled",true);
$("#primerSource"+index).val("Synthesize");
$("#primerSource_s"+index).attr("value","Synthesize");
$("#primerSource"+index).prop("disabled",true);
console.log('this is working')
}else{
for( var i = index; i < filled_rows; i++ ) {
if(document.getElementById('primerSource'+i).value != "" && document.getElementById('primerSource'+i).hasAttribute("disabled")==false){
document.getElementById('primerSource_s'+i).value = value;
document.getElementById('primerSource'+i).value = value;
console.log('primer is working')
}
} console.log('else is working')
}
}
Please help me figure out how to make that function! I am not sure if my logic makes sense or not. Any help would be nice since I have been stuck on this for a while. Thank you for your help!
This can be done using the .nextAll method:
$(document).ready(function () {
$('select[id^=primerSource-]').on('change', function(){
var selectedValue = $(this).val();
$(this).nextAll('select[id^=primerSource-]').each(function(){
if ($(this).val() !== selectedValue) {
$(this).val(selectedValue);
}
})
});
});

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

Three.js : change texture at runtime

I'm creating an UI in which the user will be able to change the texture of the selected object by clicking on the desired textures picture.
The problem is that I can only use the last texture added in the array.
Here is my php which lists the textures in my specified folder:
<ul id="textureH">
<script type="text/javascript">
texArray = [];
</script>
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
if ($extension == 'jpg'){
$texName = $dirArray[$index];
$texId = "texture". $index;
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
texArray.push(texId);
</script>
<?php
echo "<li id='".$texId."'><table><tr><td><img class='texture-image-list' src='img/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
And here's my function:
var uTexture = document.getElementById(texId);
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
var texMap = "./img/" + texName;
for (var i in texArray) {
if ((texArray[i] == texId) && (SELECTED instanceof THREE.Mesh)) {
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
}
}
I think the problem comes from the array.
Thanks to 2pha I could achieve what I wanted to do.
Here's my new code:
(The php/html)
<div class="right-panel-textures">
<h3 id="cat-hierarchy">Textures</h3>
<?php
$myDirectory = opendir('img/textures');
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
sort($dirArray);
closedir($myDirectory);
$indexCount = count($dirArray);
?>
<ul id="textureH">
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
$texName = $dirArray[$index];
$texId = "texture". $index;
if ($extension == 'jpg'){
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
</script>
<?php
echo "<li class='texture-single-item' data-texture-name='".$texName."' data-texture-id='".$texId."' id='texture-single-item'><table><tr><td><img class='texture-image-list' src='img/textures/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
</div>
(And the JavaScript)
var uTexture = document.getElementById("texture-single-item");
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
$(".texture-single-item").bind("click", function(event) {
var nameT = $(this).attr("data-texture-name");
if (SELECTED instanceof THREE.Mesh) {
var texMap = "./img/textures/" + nameT;
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
});
}
Thank you :)

nested categories dropdown in magento

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!
Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

Categories

Resources