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
Related
my problem is to get a dynamic total for each checkbox group coming from a PHP loop
unique array-items comes from mysql database loop
<?php
$price_list = array(1, 7, 8, 10, 12, 15);
foreach($price_list AS $price){ ?>
<div>
<span>Price-Group <?php echo $price;?></span>
<form method="post" action="">
<input type="text" value="20.50" id="price<?php echo $price;?>"><br>
Option 1<input type="checkbox" value="1.50" data-id="<?php echo $price;?>"><br>
Option 2<input type="checkbox" value="2.50" data-id="<?php echo $price;?>"><br>
Option 3<input type="checkbox" value="3.50" data-id="<?php echo $price;?>"><br>
<input type="text" id="total<?php echo $price;?>" value="20.50">
</form>
</div>
<hr>
<?php } ?>
and here is my problem jquery-code (i need a dynamic total)
<script>
$('input:checkbox').change(function(){
var id = $(this).attr('data-id');
var total = parseFloat($('#price'+id).val());
$('input:checkbox:checked').each(function(){
total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
});
$('#total'+id).val(total);
});
</script>
OK, I spotted a problem in your Javascript. In the middle you do:
$('input:checkbox:checked').each(function () {....});
and this function is therefore applied to all checked checkboxes. You only want to apply the function to checked checkboxes in the pricegroup, to which the checkbox that changed belongs. Something like this:
$('#form' + id + ' input:checkbox:checked').each(function () {....});
Now you don't have a form id, so I had to add that. See: code example.
Note that you don't have to give each checkbox an individual data-id, because from them you can access the form id. For instance, when a checkbox changed:
var id = $(this).parent().attr('id');
would give you the whole form id.
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();
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);
});
I have a table with a list of all my data. The data is printed in a for loop so there are many rows in the table. how can i get the userid in the row with the button clicked?
<table>
<td>
<input type="hidden" value="<c:out value="${user.id}" />" name="userId" />
</td>
<td>
<button class="btn btn-default fileUpload" data-toggle="modal" id="btnUpload" data-target="#file-modal" value="<c:out value="${user.id}" />">Upload</button></td>
</table>
and i have a modal container. When the upload button in the table is clicked, the modal will open up for a file upload.
<form action="${pageContext.request.contextPath}/UserServlet" enctype="multipart/form-data" method="post">
<input type="hidden" value="5519" name="OPS" />
<input type="hidden" name="uploadUserId" />
<div class="form-group">
File : <input type="file" class="file" name="uploadFile"><br />
<button type="submit" class="btn btn-default">Upload</button>
<br /><br />
</div>
</form>
What i am trying to do is on the click of btnUpload the value in the hidden input type userId will be copied over to the hidden value type uploadUserId
I have tried doing the following but neither works
1
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").find("#userId").text();
$("#uploadUserId").val($userId);
});
});
2
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").children()[2].text();
$("#uploadUserId").val($userId);
});
});
This will do the trick without changing the html
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).parent().prev("td").children("input:hidden").val();
$("#uploadUserId").val($userId);
});
});
Another solution by adding ID to the input element as shown below,
<input id="userVal" type="hidden" value="<c:out value="${user.id}" />"name="userId" />
then you can get the value from the following jquery
$("#userVal").val();
This should work. Just select and grab the user Id txt and then pass it to the uploadUserId value.
$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $('#userId').text();
//$("#uploadUserId").val($userId);
$('input[name="uploadUserId"]').val($userId);
});
});
UPDATE
OK. I reviewed this again using your HTML structure and got this all worked out. The code below works.
$('[type="submit"]').on('click', function(e){
e.preventDefault(); // prevents the button default action. You can remove this if you want the form to submit after click.
var $userId = $(this).prev().prev().val(), // this gets the input value. based on your html it is the previous previous element.
fix1 = $userId.replace(/(?:\..+)$/, '').split('\\'), // this is a regex that replces the file extention then splits the string on the back slash turning it into an array.
fix2 = fix1.length -1; // gets the length of the array and subtracts 1 to get the last array index of the array. This i to get the file name.
$('[name="uploadUserId"').val(fix1[fix2]); // this assigns the uploadUserId value to the name of the file using the array and the index.
});
we have list employees with email id using below code
<tbody>
<?php
$sqlquery = mysql_query("select * FROM employee");
while($row=mysql_fetch_object($sqlquery)){
?>
<tr class="gradeA">
<td><input type="checkbox" name="eid" value="<?php echo $row->emailid;?>" onclick="send_email_form_test()"><?php echo $row->name;?></td>
</tr>
<?php }?>
</tbody>
when checkbox is clicked following function call,
function send_email_form_test(){
var selected = new Array();
$("input:checkbox[name=eid]:checked").each(function() {
if($(this).val() !=""){
selected.push($(this).val());
}
});
alert(selected.join(','));
var final_email = selected.join(',');
document.getElementById("to").value =final_email;
}
after click the checkbox,email ids are appears in "to" textarea field .when i will go to second page of the employee list, i cant able to get "to" textarea field,it will empty on the second page
<div>
<label for="required">TO</label>
<textarea name="to" cols="5" rows="10"></textarea>
</div>
<div>
<label for="email">Subject</label>
<input type="text" size="80" id="subject" name="subject" >
<input type="submit" name="submit" value="submit">
</div>
how to add and remove the email ids with comma separated,when i click the checkbox.I have issue on when i will go on next page of the pagination
You can add 'this' parameter to the Javascript function as onclick="send_email_form_test(this)"> then you will get the clicked checkbox object. Then you will be able to retrieve the value of the clicked check box
I did not test it, but I think this is how you could collect emails from all pages
<?php
//...
echo '<script>window.tablePage = ', $paginator->currentPage, ';</script>';
?>
<script type="application/javascript">
//...
pageSelected = selected.join(',');
//get emails selected on other pages
allSelected = JSON.parse(localStorage.getItem('emails'));
//add currently selected emails
allSelected[tablePage] = pageSelected;
localStorage.setItem('emails', JSON.stringify(allSelected));
//output emails from all pages
document.getElementById("to").value = allSelected.join(',');
//...
</script>
(JSON library is here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js )