I'm making a custom field in a custom meta box in WordPress. I have input text fields, textareas, and checkboxes that are all working fine. I also included a browse button for the image gallery that is working.
When you click on the "Browse" button, it pulls up the WordPress media upload screen, and when you select that image, it will replace the input value (as well as an image thumbnail).
Here is the relevant part of the WordPress meta box set up.
function show_custom_fields_meta_box() {
global $post;
$meta = get_post_meta( $post->ID, 'custom_fields', true ); ?>
<input type="hidden" name="custom_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
<!-- image upload field -->
<p>
<label for="custom_fields[image]">Image Upload</label><br>
<input type="text" name="custom_fields[image]" id="custom_fields[image]" class="meta-image regular-text" value="<?php echo $meta['image']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image']; ?>" style="max-width: 250px;"></div>
</p>
}
And here's the jQuery I'm using to open the WordPress media gallery and upload the image.
<script>
/*
* Attaches the image uploader to the input field
*/
jQuery(document).ready(function ($) {
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('.image-upload').click(function (e) {
// Prevents the default action from occuring.
e.preventDefault();
var selected = $(this);
var meta_image = $('.meta-image');
// If the frame already exists, re-open it.
if (meta_image_frame) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: {
text: meta_image.button
}
});
// Runs when an image is selected.
meta_image_frame.on('select', function () {
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
$('.meta-image').val(media_attachment.url);
var imgurl = $('.meta-image').val();
$(selected).prev().val(imgurl);
$(selected).closest('div').find('.image-preview').children('img').attr('src',imgurl);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
</script>
Now, this works perfectly fine as-is. The input button has a class of .image-upload, and the input text field has a class of meta-image.
However, if I add another field...(custom_fields[image2])
<p>
<label for="custom_fields[image2]">Image Upload</label><br>
<input type="text" name="custom_fields[image2]" id="custom_fields[image2]" class="meta-image regular-text" value="<?php echo $meta['image2']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image2']; ?>" style="max-width: 250px;"></div>
</p>
The jQuery will apply to both browse buttons and text inputs, because it's a class. I know (think) I have to use some form of $(this) to get the correct button and text input, but all of my efforts have been in vain so far.
I've tried $(this).closest('.meta-image'), but that doesn't seem to work.
Thank you!
I was able to do it with this code:
var meta_image = $(this).parent().children('.meta-image');
You could use the variable selected in the select event handler.
Try this:
var metaImage = $(selected).closest('p').find('.meta-image),
imgurl = $(metaImage).val();
Related
I have made a user profile card where the user can click on choose file to select and upload an image.
Everything works fine however I would like to change it so instead of having to click on "choose file" and then click on "upload", the user can just click on the existing image and be brought to the select image screen:
and once they have selected a image and pressed open, the image is automatically changed?
This is my code to display the user profile card.
<?php
//query to see if the user has uploaded a profile picture.
$sql = "SELECT * FROM user_image WHERE userid = ?";
$stmt = mysqli_prepare($connect, $sql);
mysqli_stmt_bind_param($stmt,"i",$_SESSION['userid']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$userImage = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
?>
<h1>User's Profile</h1>
<?php if($userImage['is_set'] == 0){
echo '<img src="profile_pics/default-profile-pic.png"/>';
}
else{
echo '<img src="'.$userImage['image_dir'].'"/>';
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<button type="submit" name="submit">Upload</button>
</form>
Use a <label> (with for targeting the id on the file field):
<label for="fileField"><img src="..."></label>
<input type="file" id="fileField" name="file" accept="image/*">
You can use a <label> tag attached the file input to trigger the open box or you can use a click handler on the image that triggers a click on the file input.
document.querySelector('img').addEventListener('click', function(){
document.querySelector('h1 + img').click();
});
To get the file to upload immediately when selected you have to attach a change event handler for the image input. Then submit the form in it. You would have to change the submit button name to something other than submit to get this to work.
document.querySelector('input[type=file]').addEventListener('change', function(){
this.form.submit();
});
<button type="submit" name="upload">Upload</button>
<label for="fileField"><img src="..." height="100px" width="100px"></label>
<input type="file" id="fileField" name="file" accept="image/*" hidden="true">
Using hidden = "true", you can invisible the choose file.
Using height and width inside the img tag, you can adjust the image size.
As you can see in the above image. I have set of radio buttons, shown as picture. My client wanted to see picture instead of radio buttons. What also he wants is when user click an image (radio button), the value of that button should get displayed in the textarea field below. So user can see the value of selected radio button and also he should be able to edit it before he click save.
So user see what he selected and he can can also type before save.
I am using Jquery for this. So when user click the radio button, I capture the value the text of what user clicked and save in variable. Than I set the value of textarea field to that variable.
All works but the problem is when user select something and type something, and than if he click another picture, the field does not clear.
Question:
How I can copy the clicked value of clicked image and show in field and also allow user to type and if he click another image the field should become clear.
Here is my code
HTML
<div class="text-center">
<h4>Select reason</h4>
<form id="timer-reason">
<div class="row">
<div class="col-md-12">
<?php
while ($row = mysqli_fetch_assoc($timer_reasons)) {
?>
<label class="select-reason" value="<?php echo $row['description_tmr']; ?>" id="<?php echo $row['id_tmr']; ?>">
<input type="hidden" id="reason-id" value="<?php echo $row['id_tmr']; ?>">
<input type="radio" name="ReasonSelect" value="<?php echo $row['description_tmr']; ?>" />
<img src="../../css/timer-reasons/<?php echo $row['image_tmr']; ?>" style="width:30%;" class="TimerReason">
</label>
<?php
}
?>
<div class="form-group">
<textarea class="form-control" id="reason" value="" rows="2"></textarea>
</div>
</div>
</div>
</div>
JQUERY
$('input:radio').click(function() {
var reasonvalue=$(this).attr("value");
$("#reason").text(reasonvalue);
});
This is due to how the browser displays textarea's value that is supplied by putting text between the opening / closing tags, setting innerText / textContent
<textarea>Value between tags</textarea>
And a value supplied by the value property.
<textarea id="reason"></textarea>
document.getElementById('reason').value = "Value by property";
You can set the innerText / textContent multiple times, but as soon as it gets a set value property, which also happens when the user starts typing, changing the innerText / textContent will no longer change the visible text shown. The actual property is changed though.
var reasonTextarea = document.getElementById('reason');
var tcBtn = document.getElementById('tcTest');
var tcBtn2 = document.getElementById('tcTest2');
var propBtn = document.getElementById('propTest');
tcBtn.addEventListener('click',function(){
reason.textContent = "textContent set";
});
tcBtn2.addEventListener('click',function(){
reason.textContent = "textContent set again";
});
propBtn.addEventListener('click',function(){
reason.value = "value property set, now try typing something and/or hitting the change by textContent button again.";
});
<textarea id="reason" rows=5 cols=40>Test value 1</textarea>
<button id="tcTest">Click to change value by textContent</button>
<button id="tcTest2">Click to change value by textContent again</button>
<button id="propTest">Click to change value by property</button>
And this is what is happening with your code, you use jQuery's .text() method which changes the textContent of the textarea. Which will work as long as you never set the value property or the user never types in the textarea.
To combat this you should change the value of the textarea by changing the value property instead of the textContent property.
jQuery('#reason').val('New value');
Try this:
$(function () {
$('[name=ReasonSelect]') // bind event on all inputs with name RadioSelect
.on('change', function() { // on a change execute the function
var v = $('[name=ReasonSelect]:checked'); // get the selected value
$("#reason").val( v ); // put the value in #reason.
});
});
Try Below code. It Should work
$('input[type=radio]').click(function() {
var reasonvalue = $(this).attr("value");
$("#reason").val(reasonvalue);
});
1)i am adding image and its title in database
but if i submit form for first time it works but again without selecting the image when its pre selected from first submit
2) submiting form 2nd time takes image value null or is empty(updating image)
<form method="post" enctype="multipart/form-data">
<div id="photoselect_box">
<h5 id="logo_head">Profile Image</h5>
<script>
function profile_imagee(input){
$('#profile_image')[0].src = (window.URL ? URL :webkitURL).createObjectURL(input.files[0]);
}
</script>
//input image preview
<img src="<?php $path = "download/items/$uid/"; echo $path.$userRow['profile_image']; ?>" id="profile_image" alt="profile photo" name="profile_image" />
<input type="file" id="img_file" name="profile_image" onChange="profile_imagee(this);"
value="<?php echo $userRow['profile_image']; ?>" />
</div>
// i am able to update this input after clicking submit
<input type="text" id="download_content1" name="download_content1" value="<?php echo $userRow['download_content1']; ?>" >
</form>
i cannot update the image value in database after submiting form for 2nd time
php code
include_once '../../database/conn.php';
$res=mysqli_query($bd,"SELECT * FROM organisation);
$userRow=mysqli_fetch_array($res);
$email=$userRow['email'];
if (isset($_POST['register'])){
//inserting logo image
$profile_image=$_FILES['profile_image']['name'];
$profile_image_temp=$_FILES['profile_image']['tmp_name'];
// changing the destination required folder according to users unique id
$path = "download/items/$uid/";
#mkdir($path, 0666, true); // Create upload folder.
move_uploaded_file($profile_image_temp,$path.$profile_image);
//updating image in database
$insert="UPDATE organisation SET profile_image= '$profile_image',download_content1 = '$download_content1 '
WHERE email = '$email'";
$insert_pro = mysqli_query($bd,$insert);
}
I have the next PHP/HTML code for upload an image:
<label>Image (*)</label>
<!-- if image exists, show it -->
<?php if($category->getImage() === null) : ?>
<input type="file" name="image" id="image" required>
<?php else : ?>
<p><img src="../uploads/images/<?php echo $categoria->getImage(); ?>"></p>
<input type="file" name="image" id="image">
<?php endif; ?>
And I want to validate it using JavaScript
// Validate image
image = document.getElementById("image").value;
if (!image) {
window.alert("You must select a file for the image.");
document.getElementById("image").focus();
return false;
}
The image is required. If you create a new registry it sets all of its atributes to null, including the image. Then, the image is not show and you can set it in the form. If you want to update them, the form shows the current imagen but you don't have to update it if you don't want to.
I need to validate if the file hasn't been uploaded and the value is null it means that the user is creating a new registry and the image is required. If the file hasn't been uploaded but its value isn't null, the user is updating the registry and it isn't required to upload an image.
Thanks in advance and sorry for my bad english.
You can add id to the image
<img id="foo" src="../uploads/images/<?php echo $categoria->getImage(); ?>">
and check if it's in the DOM:
if ($('#foo').length) {
// image is there
}
or without jQuery:
if (document.getElementById("foo")) {
// image is there
}
I have PHP code that spits out an HTML table. In this row, I have an input type=\"checkbox\" that sends the id=\"$Row[ID_NUMBER]}\" to a modal window. Here is the echo statement that prints the row data with the checkbox. Take notice of the extra data field in the row.
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[ID_NUMBER]}\" data-info=\"{$Row[BOL_NUMBER]}\" name=\"checkMr[]\" /></td></tr>";
Here is the javascript the retrieves the id=\"{$Row[ID_NUMBER]}\" and displays it in the modal window:
<script type="text/javascript">
$(function modalForm(){
$('a').click(function modalForm(){
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each (function modalForm(){
selectedID.push(this.id);
});
$(".modal-body #idNumber").val( selectedID );
});
});
</script>
Of course there is a button that calls the javascript function via onclick="modalForm();" that I don't think I need to show you. However, here is where the modal prints the #idNumber:
<label>Container Selected</label>
<input disabled type="text" name="idNumber" id="idNumber" placeholder="no containers selected" />
What I need to do on top of retrieving the id from the datatable is retrieve the data-info=\"{$Row[BOL_NUMBER]}\" and send it to the modal window. I have an input field for boNumber that goes right underneath idNumber:
<label>Bol Selected</label>
<input type="text" name="bolNumber" id="bolNumber" />
I know this can be done within the same javascript function above. Any help would be appreciated.
$(':checkbox[name="checkMr[]"]:checked').each (function modalForm(){
selectedID.push(this.id);
// get the data-info from checkbox and set value in modal
$("#bolNumber").val($(this).attr('data-info'));
});