Name change from one element to another and value store - javascript

i need to get the name and value from li element and display it after selection as the button value, what i need more is for that single value to be stored in a php var for latter submit, i got this far but now i am stuck and keep getting 1 size only
CODE
<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span>
</button>
<ul class="dropdown-menu size-list" role="menu">
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
foreach ($productAttribute['values'] as $attribute) {
$attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
}
}
$key = "Size";
foreach($attributeOptions[$key] as $size){ ?>
<li id="<?php echo $size; ?>" onclick="changeName()"><?php echo $size; ?></li>
<?php }
} ?>
</ul>
</div>
<script>
function changeName() {
document.getElementById("changename").innerHTML = "<?php echo $size; ?>";
}
</script>

OK, well there are 2 issues i can see. 1st that your third foreach loop looks like it should be nested within the others, but its not.
The second issue is that that you are missunderstanding how php and js work. Php is ran on the server before the page is rendered, so the value of $size in your js function will be whatever the LAST value of was.
To fix this, 1st nest the foreach correctly (when using php inline with html, i find its best to use the template syntax for blocks - eg if: endif;, foreach: endforeach; to aid readability), then adjust your js function to take a parameter, and pass that parameter in the onclick event by grabing the clicked elements id:
<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span>
</button>
<ul class="dropdown-menu size-list" role="menu">
<?php
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) :
foreach ($productAttribute['values'] as $attribute) :
$attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
$key = "Size";
foreach($attributeOptions[$key] as $size):?>
<li id="<?php echo $size; ?>" onclick="changeName(this.id);"><?php echo $size; ?></li>
<?php endforeach;
endforeach;
endforeach;
?>
</ul>
</div>
<script>
function changeName(size) {
document.getElementById("changename").innerHTML = size;
}
</script>

Related

jQuery Hide Div of associated PHP MySQL results in While Loop

Having an issue. I need to remove the associated element on the click of a button from a list of results provided by a MySQL query. Only the first image is being hidden on the click of the remove button. The rest of the images returned do nothing.
Here is my code :
PHP:
<?php
while ($image_row = mysqli_fetch_array($image_result)) { ?>
<span class="listing_image_preview" id="image_<?php echo $image_row['id']; ?>">
<img src="<?php echo $image_row['image_thumb']; ?>" style="border:6px solid #EEE; margin:6px;" />
<button id="remove_image" class="btn btn-default btn-xs" imageId="<?php echo $image_row['id']; ?>">Remove</button>
</span>
<?php
}
?>
jQuery:
$(document).ready(function() {
$("#remove_image").click(function() {
var image_id = $(this).attr('imageId');
$('#image_'+image_id).hide();
})
});
All your buttons have the same id:
<button id="remove_image"
And your jquery script will only find one element with the following selector:
$("#remove_image")
Here's one way to solve it:
Add remove_on_click to the button's class (I also made the id's unique)
<?php
while ($image_row = mysqli_fetch_array($image_result)) { ?>
<span class="listing_image_preview" id="image_<?php echo $image_row['id']; ?>">
<img src="<?php echo $image_row['image_thumb']; ?>" style="border:6px solid #EEE; margin:6px;" />
<button id="remove_image_<?php echo $image_row['id']; ?>" class="btn btn-default btn-xs remove_on_click" imageId="<?php echo $image_row['id']; ?>">Remove</button>
</span>
<?php
}
?>
In your jquery script select on class remove_on_click:
$(document).ready(function() {
$(".remove_on_click").click(function() {
var image_id = $(this).attr('imageId');
$('#image_'+image_id).hide();
})
});

Send parameter to the PHP-function from JavaScript

I've a such PHP-script:
<?php
$menuItemList = getSubPkgCategForDDList(echo "<script>showSubCatForMenuItem();</script>");
if(isset($menuItemList)){
foreach($menuItemList as $u){
?>
<p><span contenteditable="true"><?php echo $u->name ?></span><button type="button" class="btn btn-danger btn-xs" onclick="deleteCategory(<?php echo $u->pkg_cat_ddlist_id ?>)">Delete</button>
<button type="button" class="btn btn-success btn-xs" onclick="editCategory(<?php echo $u->pkg_cat_ddlist_id ?>,<?php echo "'".$u->name."'" ?>)">Save</button></p>
<?php
}
}
?>
Function getSubPkgCategForDDList must generate html-code,so it depends from parameter, which is send to this function.
I get this parameter from such js-function showSubCatForMenuItem():
function showSubCatForMenuItem(){
console.log($('#menuItem').val());
return $('#menuItem').val();
}
This function takes data from such dropdown list:
<select id="menuItem" onchange="showSubCatForMenuItem()">
<?php
$itemList = getPackCategoriesForAsideMenu();
if(isset($itemList)){
foreach($itemList as $u){
?>
<option value="<?php echo $u->pkg_cat_ddlist_id ?>"><?php echo $u->name ?></option>
<?php
}
}
?>
</select>
How to do that parameter transfer is correctly, when I load page and select item from dropdown list? Sorry for my English.
You should take advantage of $_SESSION in this case. Now print out the drop down :
<select id="menuItem">
<?php
$itemList = getPackCategoriesForAsideMenu();
if(isset($itemList)){
foreach($itemList as $u){
echo'<option value="'.$u->pkg_cat_ddlist_id.'">'.$u->name.'</option>';
}
}
?>
</select>
Write the JS script :
$("#menuItem").live('change',function(){
var val = $(this).val();
$.post('change.php',{data:val},function(){
// Do some
});
});
And create a php file named change.php :
<?php
session_start();
if(!empty($_POST['data'])){
$_SESSION['menu_sltd'] = (int) $_POST['data']; // It makes sure that the data sent is integer / number
}
?>
Now, change your main script to :
<?php
session_start();
$menu_sltd = (!empty($_SESSION['menu_sltd']) ? $_SESSION['menu_sltd'] : 'default id'); // Default id is the default menu id if it's blank
$menuItemList = getSubPkgCategForDDList($_SESSION['menu_sltd']);
if(isset($menuItemList)){
foreach($menuItemList as $u){
echo'
<p>
<span contenteditable="true">'.$u->name.'</span>
<button type="button" class="btn btn-danger btn-xs" onclick="deleteCategory('.$u->pkg_cat_ddlist_id.')">Delete</button>
<button type="button" class="btn btn-success btn-xs" onclick="editCategory('.$u->pkg_cat_ddlist_id.',\''.$u->name.'\')">Save</button>
</p>';
}
}
?>
GOOD LUCK,, glad to help you. Don't give up
In javascript function showSubCatForMenuItem() you can set the value of selected item in some hidden field on every change event the value selected by user will get updated, then while saving the use this value that is saved in the hidden field.

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

jQuery addClass within a foreach loop

I have a few foreach loops with a trigger and a content div. The intent is for the trigger to be clicked, then addClass to content div, making it visible on screen.
foreach markup
<?php foreach( $posts as $post ) : ?>
<a class="slide-trigger" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
<span>
<?php
$speakers = get_field('speakers');
?>
<?php if( $speakers ): ?>
<ul class="flat">
<?php foreach( $speakers as $speaker ): ?>
<li>
<a href="<?php echo get_permalink( $speaker->ID ); ?>">
<?php echo get_the_title( $speaker->ID ); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</span>
<div class="slide" id="loc<?php echo $post->ID;?>">
<div class="close"></div>
<?php echo $post->post_title;?>
<?php echo $post->post_content;?>
</div>
<?php endforeach; ?>
jQuery
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id^='loc']").addClass("open");
})
$(".close").click(function(){
$(".slide").removeClass("open");
});
What I'm looking for is each slide-toggle to trigger it's slide.
Any thoughts?
The ID is in the href, so just grab it and remove the #loc prefix, then you can select the corresponding slide to open. Also this way, the startsWith selector is no longer required.
$(".slide-toggle[href^='#loc']").click(function(e){
e.preventDefault();
$(".slide[id='loc" + this.href.replace('#loc', '') + "']").addClass("open");
})
Having to parse out the ID, then concatenate like this seems a bit hacky. It would be nicer to use data-* attributes.
Link:
<a class="slide-trigger" data-id="<?php echo $post->ID;?>" href="#loc<?php echo $post->ID;?>"><?php the_title(); ?></a>
Slide:
<div class="slide" data-id="<?php echo $post->ID;?>" id="loc<?php echo $post->ID;?>">
jQuery:
$(".slide-toggle[data-id]").click(function(e){
e.preventDefault();
$(".slide[data-id=" + $(this).data('id') + "]").addClass("open");
})
#MrCode had two great solutions to this. The data-id method is a bit more elegant and what I went with.
Note, the $post->ID is a number which just won't work as an id= - https://css-tricks.com/ids-cannot-start-with-a-number/ - and was causing the issue where things just wouldn't work.
The answer; follow #MrCode's method of using a data attribute. It's elegant and works great w/ the loop.

Trying to display data shown depending on what users click

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>
Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.
Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>
Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>
You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Categories