JavaScript Function Call With OnClick - javascript

I have a simple function that works when it is hard coded, but when I try to pass a second parameter into it, it doesn't work. I am calling the function with the onclick and using the id => thumbnail to get the value. Any suggestions?
Hard Coded Example (Works)
<script>
function clearFileInputField(tagId) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.thumbnail').val("");
}
</script>
<div id="thumbnail_div" class="row">
<?php echo $form->labelex($model,'thumbnail'); ?>
<?php echo $form->textfield($model,'thumbnail', array(placeholder => "No file chosen", readonly => true, 'class' => 'thumbnail')); ?><br>
<?php echo $form->filefield($model,'thumbnail'); ?>
<?php echo $form->error($model,'thumbnail'); ?>
<input type="checkbox" onclick = "clearFileInputField('thumbnail_div')" href="javascript:noAction();"> Remove Thumbnail
</div>
Parameters Passed (Not Working)
<script>
function clearFileInputField(tagId, div) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.div').val("");
}
</script>
<div id="thumbnail_div" class="row">
<?php echo $form->labelex($model,'thumbnail'); ?>
<?php echo $form->textfield($model,'thumbnail', array(placeholder => "No file chosen", readonly => true, 'id' => 'thumbnail')); ?><br>
<?php echo $form->filefield($model,'thumbnail'); ?>
<?php echo $form->error($model,'thumbnail'); ?>
<input type="checkbox" onclick = "clearFileInputField('thumbnail_div', 'thumbnail')" href="javascript:noAction();"> Remove Thumbnail
</div>

You are almost there. In your code, the paramenter div is converted to string. Instead of that, try the code given below,
<script>
function clearFileInputField(tagId, div) {
document.getElementById(tagId).innerHTML =
document.getElementById(tagId).innerHTML;
$('.'+div).val("");
}
</script>

$('.div').val("");
^^^^^^
That's a string, not a variable. You're trying to find elements that have class="div".
You need to concatenate the variable with a string containing the dot.:
$('.' + div).val("");

$('.div').val("");
That part is close but not going to work as you might have intended. You instead should have it one of two ways,
$('.'+div).val("");
or,
$(div).val("");
With option 1, you are using a string for the period and concatenating it with the value of the variable div
With option 2, you will need to change the passed parameter to include a period before it.

You could easily get rid of your inline handler and just create a simple event handler.
jQuery(function(){
// Bind a handler to any button with the class remove_thumbnail
$('.remove_thumbnail').change(function(){
if (this.checked) {
$(this)
// go up to parent row
.parents('.row')
// find the thumbnail
.find('.thumbnail')
.val("");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thumbnail_div" class="row">
<input type="text" class="thumbnail" value="foo">
<input type="checkbox" class="remove_thumbnail"> Remove Thumbnail
</div>
The advantages here are that you separate content and behavior and do not introduce functions into the global scope.

try this (with script placed underneath the markup):
<div id="thumbnail_div" class="row">
<?php echo $form->labelex($model,'thumbnail'); ?>
<?php echo $form->textfield($model,'thumbnail', array(placeholder => "No file chosen", readonly => true, 'id' => 'thumbnail')); ?><br>
<?php echo $form->filefield($model,'thumbnail'); ?>
<?php echo $form->error($model,'thumbnail'); ?>
<input type="checkbox" onclick = "clearFileInputField('thumbnail_div', 'thumbnail')" href="javascript:noAction();"> Remove Thumbnail
</div>
<script>
function clearFileInputField(tagId, div) {
document.getElementById(tagId).innerHTML = document.getElementById(tagId).innerHTML;
$('.'+div).val("");
}
</script>

Related

I can't take the value attribute on button | jQuery AJAX

I made ajax script for delete button and have data attribute based on id on the table in database. This is the HTML :
<textarea name="komentar" id="komentar" cols="30" rows="10"></textarea><br>
<input type="submit" name="submit" id="submit" value="Submit"><br>
<br><br><hr><br>
<!-- Komentar akan ada di dalam sini -->
<div id="komentar_wrapper">
<?php
include_once 'db.php';
$query = "SELECT * FROM komentar ORDER BY id DESC";
$show_comments = mysqli_query($db, $query);
foreach ($show_comments as $comment) { ?>
<p id="komentar_<?php echo $comment['id']; ?>"><?php echo $comment['komentar']; ?>
<!-- data-id-> data attribute, buat spesifik id mana yang mau di hapus -->
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment['id']; ?>">Delete</button>
</p>
<?php } ?>
</div>
And when i try to console the data-id, it wont show the value on console. This is the script :
$(".hapus_komentar").on("click", function() {
console.log($(this).attr("data-id"));
});
When i click the button it say undefined, i think it should print the id based on button data-id
try this i have prepared a demo code for you and runs ok
<?php
$as = array(1,2,3,4,5,6,7);
foreach ($as as $comment) { ?>
<p id="komentar_<?php echo $comment ?>"><?php echo $comment; ?>
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment; ?>">Delete</button>
</p>
<?php
}
?>
<script type="text/javascript">
$(".hapus_komentar").on("click", function() {
alert($(this).attr("data-id"));
//console.log($(this).attr("data-id"));
});
</script>
use Jquery.data(). and use event delegation since your button is generated dynamically.
$(document).on("click",".hapus_komentar",function() {
console.log($(this).data("id"));
});
You can use $(this).data("id") to get the id.
Your code is correct. Just check in HTML weather data-id will have value or not. Maybe that's the reason you are not getting proper value. As well you have taken that button in the loop so make sure on individual button click you will get all buttons data-id.
$(".hapus_komentar").on("click", function() {
console.log($(this).data("id"));
});
now use this.
$(document).on("click",".hapus_komentar",function() {
console.log($(this).attr("data-id"));
});

Get the value through looping in jquery

for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
}
Jquery :
$('.question_title').click(function () {
var value = $('#question_id').val();
alert(value);
});
Friends in this code question_id will be carrying different values for the looping . Here I have writtern code to get the value according to the LOOPING on click of ahref class I would like to fetch the value of hidden value for example in the first iteration title is cow on click ahref it should alert 0 (question_id value). on click on 2nd title cat it should get alert 1 like on clicking 5 different title it should display 0-4 respectively but now onclick on different title it alerts only 0 not the other values . could any one suggest me how to achieve it .
Get the parent h2 and then next .question_id like following.
$('.question_title').click(function() {
var value = $(this).parent().next('.question_id').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Title 0</h2>
<input type="hidden" name="question_id" value="0" id="question_id" class="question_id">
<h2>Title 1</h2>
<input type="hidden" name="question_id" value="1" id="question_id" class="question_id">
BTW you are using same id question_id for multiple elements.
As 'id' is unique value, it will get only the first element.
Try this:
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
}
Jquery :
$('.question_title').click(function()
{
alert(event.target.id);
});
For
<?php
for($i=0;$i<5;i++)
{
?>
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
<?php } ?>
And in script use
$('.question_title').click(function() {
alert($(this).attr("data-tell"));
});
You are having the same id question_id in all five hidden fields.
you can have it like this..
for($i=0;$i<5;i++)
{
echo '<h2>'.$value['asked_title'].'</h2>';
}
jquery
$('.question_title').click(function()
{
var value = $(this).data('value');
alert(value);
});

Change paragraph attribute to input tag

I tried following code in which I am trying to change paragraph tag to input fields through jquery on button click. I want my values to retain in the textbox when I click the button. Unfortunately, it isn't working! Here I have tried it with just name field. Any suggestions please.
code
<div id="menu2" class="tab-pane fade">
<h3>Address Book</h3>
<p>Default delivery address</p>
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p class="name" id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p class="mail"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p class="tele"><?= $row['phone'] ?></p>
<h5>Address:</h5><p class="addres"><?= $row['address'] ?></p>
<h5>City:</h5><p class="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="update" value="Update Address" >
</div>
Jquery
<script src="js/jquery-1.6.2.js"></script>
<script>
$(document).ready(function() {
$('#update').click(function()
var input = $("<input>", { val: $(this).text(),type: "text" });
$('#name').replaceWith(input);
input.select();
});
});
</script>
Your code works, bar two errors. Firstly, you're missing a { after the click handler function definition. Secondly, this within the #update click handler refers to the button element, yet you're trying to read the val() of the #name input, so you need to change the selector. With that in mind, try this:
$('#update').click(function() {
var $name = $('#name');
var $input = $("<input>", {
val: $name.text(),
type: "text"
});
$name.replaceWith($input);
$input.select();
});
Working example
I would also be wary of having duplicated id attributes in your page as you are defining the elements in a loop. Should there be multiple rows returned from your query, then you will have multiple elements with the same id in the document which will lead to possible errors as the HTML will be invalid.

Drupal/Jquery: hide parent div if child is empty

I am having difficulty working this out. What I wish to achieve is when works-left and works-right are empty (keeping in mind it functions using drupal pre-processed code) the parent div (latest-works-container) will disappear.
I was wondering if there were somesort of solution to the problem. The thing that came to me was editing the template.php code that is found in bartik, or some other possible solution?
function hybrid_preprocess_html(&$variables) {
if (!empty($variables['page']['featured'])) {
$variables['classes_array'][] = 'featured';
}
if (!empty($variables['page']['services_first'])
|| !empty($variables['page']['services_second'])
|| !empty($variables['page']['services_third'])
|| !empty($variables['page']['services_fourth'])) {
$variables['classes_array'][] = 'services';
}
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php print render($page['portfolio_works_first']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_second']); ?>
</div>
<div class="works-left">
<?php print render($page['portfolio_works_third']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_fourth']); ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->
Your element content comes from PHP, so you have no need to remove div using jQuery.
Instead, you should edit your view file. So for example you have you render() method, which gives your the content of div.
$contentBlockFirstLeft = render($page['portfolio_works_first']);
$contentBlockSecondLeft = render($page['portfolio_works_third']);
$contentBlockFirstRight = render($page['portfolio_works_second']);
$contentBlockSecondRight = render($page['portfolio_works_fourth']);
$isLeftBlockEmpty = empty($contentBlockFirstLeft) && empty($contentBlockSecondLeft);
$isRightBlockEmpty = empty($contentBlockFirstRight) && empty($contentBlockSecondRight);
$showAllBlocks = true;
if ($isLeftBlockEmpty && $isRightBlockEmpty) {
$showAllBlocks = false;
}
So you already know all needed information to output your elemnt, so for example you will have next view. Please feel free to change variable names according to business logic needed, those are just dummy names.
<?php if ($showAllBlocks): ?>
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php echo $contentBlockFirstLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockFirstRight; ?>
</div>
<div class="works-left">
<?php echo $contentBlockSecondLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockSecondRight; ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->
<?php endif; ?>

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