View the value of selected radio button in an input field - javascript

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);
});

Related

HIdden input value, non unique ID in form loop

I'm trying to prep forms with multiple (dynamic) inputs to insert correctly via ajax.
Currently, using my php loop, I have 4 div/forms. Each form has a starting input, and upon clicking the moreItems_add button, it dynamically adds another input, up to 10 per form/div.
This works fine. But I added a variable and console.log to log the value of my hidden input though, which should be getting an ID (<?php echo $ticker['ticker'] ?>) for each form, but it's currently only logging '1'. So when I clicked the button in the first form it looked right, but when I click the others, it's still 1. I think this is because I don't have a unique ID on the hidden input?
How can I change the way I'm keeping track of the hidden input so that I can make an ajax call that will only make an insert on the inputs of the given form WITH the correct ticker ID?
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
To generate a unique id attribute you should append your ticker value from php to... the id attribute. Or if not the ticker value, at least something that makes it unique. But you don't really need to.
Since all your elements are wrapped in a form tag and are at the same level, you can find to which ticker corresponds the clicked button by finding the hidden input among its siblings:
var tickerID = $(this).siblings('input[name="tickerID"]').val();

set input value equal to div content

I've a some dynamic buttons and when I click on them they display the price inside the div with id="prezzo".
but now I need that, when I click on one of those buttons, they fill the hidden value field of the form with the same "data-prezzo".
Basically I want that even the form value is dynamic like the div with id="prezzo"
Is this possible?
$(document).ready(function() {
$("input[id^=service]").on("click", getCheck);
$(".event-hook-class").on("click",function(e) {
e.preventDefault();
$(".event-hook-class").removeClass("active");
$(this).addClass("active")
$("#prezzo").html($(this).data('prezzo') + ' €');
$("#form-prezzo").setAttribute("value", $(this).data('prezzo'));
$("#piano").html('piano: ' + $(this).data('piano'));
getCheck(); // will add this and the checkboxes
});
getCheck(); // initialise on page load
});
<?php
echo '<button type="button" class="event-hook-class simple-text piano" id="'.$id_appartamenti.'" data-prezzo="'.$prezzo_piano.'" data-piano="'.$piano.'">.$id_appartamenti.' <br> piano '.$piano.'<br> prezzo '.$prezzo_piano.' €</button><br>';
?>
<p class="paragraph" id="prezzo"> €</p>
<form>
<input type="hidden" value="" id="form-prezzo" data-name="prezzo">
</form>
and a form with this imput field
You can use val() to set the input's value:
$("#form-prezzo").val(prova)
And also you have a double id attribute in you hidden field which is invalid
if you are getting the value of a div or p tag you can get it using the following code.
$("#prezzo").text()

Only apply image upload url to specific input field

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();

How can a radio button trigger a counter and print output to the viewer's box?

How can I pass a javascript variable into the text value box below four radio buttons when one of them is selected.
//something like
var new ="somethign";
<a href="javascript:insertText(' var new ' ,'user_location');"
onClick="void(0)">Insert 'Hello'</a>
...so that when they click it, the counter and or a message is displayed in an empty form box...?
I want to output the contents of the variable. into a form-field entry type of box.
Using jQuery you could do something like this:
from your question i'm not getting much of idea.but if you want to put some text to div on click of radio button then may be try in this way:
<script>
$(document).ready(function(){
$('input[type=radio]').click(function() {
$('#viewer').html($(this).val());
});
});
</script>
<input type='radio' name ="r"value="something1">1
<input type='radio'name ="r" value="something2">2
<input type='radio' name ="r"value="something3">3
<input type='radio'name ="r" value="something4">4
<div id="viewer" ></>

Jquery - Append value to Paragraph

I have 4 groups of data that are tied to a click-bind event. I'm trying to add the value from a hidden field contained within each group to a paragraph later in the page, so that when the checkbox is clicked from one or more groups of data, the value from the hidden field displays within the paragraph area.
I'd also like to get it so that when the checkbox is unclicked, it removes the value from the paragraph, but for now I'm just trying to get the value to display when the checkbox is clicked.
Here's what I've tried:
This is the hidden field within the group of data that stores the value:
<input id="servicename_<?php echo $i;?>" name="servicename_<?php echo $i;?>"
type="hidden" value="<?php echo $service->PRODUCT;?>"></input>
This is the click-bind event:
$('input[id^=ckNow_]').each(function(){
$(this).bind('click',function(){
if($(this).prop('checked'))
{
var servicename = '#servicename_'+$(this).attr('value').split("_");
ServiceName += servicename;
$('#lblServiceName').append($(ServiceName));
EDIT to add the checkbox that is within each group:
<input type="checkbox" id="ckNow_<?php echo $i;?>" name="ckNow[<?php echo $i;?>]">
</input>
And then the paragraph text:
<p id="lblServiceName">Service Name
<input type="hidden" id="servicename" value="0"></input>
</p>
What am I doing wrong and how can I fix it? All responses are very appreciated and I'm completely open to any and all suggestions. Thank you.
Try
<p id="lblServiceName">Service Name
<span></span>
<input type="hidden" id="servicename" value="0"></input>
</p>
then
jQuery(function ($) {
var $checks = $('.group-data input[name^="ckNow["]').change(function () {
var vals = $checks.filter(':checked').map(function () {
return $(this).closest('.group-data').find('input[id^=servicename_]').val()
}).get();
$('#lblServiceName span').text(vals.join(', '))
})
})
Demo: Fiddle

Categories

Resources