Ok, say I have a checkbox such as this:
<input type="checkbox" value="1" class="discount_select" name="select[101132]">
...and 3 text fields like this:
<input type="text" name="start[101132]">
<input type="text" name="end[101132]">
<input type="text" name="discount[101132]">
I am running some code right now that will update the text field values if the checkbox is checked, however I'm not sure if or how you can target the correct fields as they all have different ID's.
So I basically have this code to loop through the checked boxes, but not sure how to make updates to the correct text fields:
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
// How can I target the correct fields/ID's here?
});
Try
// Get values
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var num = this.name.substring(7, this.name.length - 1);
$('input[name="start[' + num + ']"]').val(start)
$('input[name="end[' + num + ']"]').val(end)
$('input[name="discount[' + num + ']"]').val(discount)
});
Change the name and ids of your fields to make it simpler
<input type="checkbox" value="1" class="discount_select" id="101132" name="select_101132">
<input type="text" name="start_101132">
<input type="text" name="end_101132">
<input type="text" name="discount_101132">
Then:
var discount = $('#apply_discount').val();
var start = $('#apply_start_date').val();
var end = $('#apply_end_date').val();
$('.discount_select:checked').each(function() {
var select_id = this.attr("id");
$('[name=start_'+select_id+']').val(start);
$('[name=end_'+select_id+']').val(end);
$('[name=discount_'+select_id+']').val(discount);
});
Related
I have to generate multiple input fields dynamically for each time user clicks "add" button and I was successfully able to get them. Each contact should have this radio input field in different different name so I've created a name in an array form.
Here's what I have so far and I wonder how I'm supposed to get the radio value for each person:
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
options = '<p>Visit Type:
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Student" required>Student</label>
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$(options).fadeIn("slow").appendTo('.companion');
return false;
}
});
$('.c_visittype' + count).on('click', function(){
$('input:radio[name="c_visittype"]').attr('checked', 'checked');
});
Each person should get a choice of either 'student' or 'visitor' and I have to get this value for multiple persons whenever more person fields created.The reason why I put field's name as an array is to iterate it in the next page by php.
<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
var options = '<p style="display: none">Visit Type:<label class="radio-inline"> <input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Student" required>Student</label> <label class="radio-inline"><input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$('.companion').append(options);
$(".companion p:last").fadeIn();
}
});
});
</script>
<button id="add">add</button>
<div class="companion">
</div>
$('input[name=c_visittype[]]:checked').val();
That's how you access the value of a checked radio button with jQuery.
var inputValues = [];
$('.c_visittype:checked').each(function() {
inputValues.push($(this).val());
});
// Your code using inputValues
For update on changes:
$(function() {
$('.c_visittype').click(function(){
// Insert code here
}
)});
Make sure to move the numbering from the class attribute to the name attribute (like it was, everything was part of the same set of options). Also, put the whole string on 1 line.
Suppose I have two checkbox like these (can be 100 checkboxes as it will be coming in a while loop)
<input type="checkbox" value="20" data="Apple">
<input type="checkbox" value="30" data="Mango">
And I have two textboxes where I want to output values 20+30 = 50 and Apple, Mango.
<input type="text" id="value1"> // to output sum of values i.e., 50
<input type="text" id="value2"> // to output comma separated data values Apple, Mango on select
Here I am able to do the first operation. But I am not sure how to do the second one. what I want is when I check the boxes its sums values and outputs it on 1st text box and when unchecks any box it deducts the values back (its already working as I was able to do it) and the second box should output values Apple, Mango when both boxes are checked respectively. If any box is unchecked say box with data value Mango then the textbox value will become Apple (even comma gets removed) only. How to do this? Here is my currennt jQuery code below for completing the 1st operation. How to do the second one? What else should I add here in this code?
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
});
});
Try this
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var txt = '';
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
txt += $(this).attr('data')+', ';
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
$("#value2").val(txt.slice(0,-2));
});
});
Check if below code works for you!
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var dataval = "";
$('input:checkbox:checked').each(function(){
var val = $(this).val();
total += isNaN(parseFloat(val)) ? 0 : parseInt(val);
dataval += $(this).attr('data') +", ";
});
$("#value1").val(total);
$("#value2").val(dataval.slice(0,-2));
});
});
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<input type="checkbox" value="20" data="Apple">
<input type="checkbox" value="30" data="Mango">
<input type="text" id="value1"> // to output sum of values i.e., 50
<input type="text" id="value2">
You should use data-* prefixed custom attributes to store arbitrary data, which can be fetched using $.fn.data(key).
$(document).ready(function() {
$('input[type=checkbox]').change(function() {
var $elem = $('input:checkbox:checked'),
$amount = $("input[name=amount]"),
$costdisplay = $("#costdisplay"),
dataValues = [],
total = 0;
if ($elem.length) {
$('input:checkbox:checked').each(function() {
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
dataValues.push($(this).data('value')); //Iterate and populate the array from custom attribute
});
}
$amount.val(total);
$costdisplay.val(dataValues.join(','));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="20" data-value="Apple">Apple<br/>
<input type="checkbox" value="30" data-value="Mango">Mango<br/>
<input type="text" name="amount"> <br/>
<input type="text" id="costdisplay"> <br/>
While calculating the total amount also make string having the data value with comma separator.
Use the below code snippet for it:
$(document).ready(function(){
$('input[type=checkbox]').change(function(){
var total = 0;
var data = '';
$('input:checkbox:checked').each(function(){
total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
if(data) {
data += ','+ $(this).attr('data');
} else {
data += $(this).attr('data');
}
});
$("#costdisplay").html(total);
$("input[name=amount]").val(total);
$("#value2").val(data);
});
});
I'm currently using the following solution to generate a number based on user input into two form fields http://jsfiddle.net/A3qat/5/
$("#download, #contention").keyup( function(){
var n1 = $("#download").val();
var n2 = $("#contention").val();
var result = n1/n2;
$("#label").text(result);
});
So, n1/n2 = n3
How can I modify this to show the output (n3) in a separate input form field underneath rather than plain text
Fiddle: http://jsfiddle.net/A3qat/49/
You should use .val()
$("#field1, #field2").keyup( function(){
var n1 = $("#field1").val();
var n2 = $("#field2").val();
var result = n2/n1;
$("#label").val(result);
});
Replace your label with input and replace $("#label").text(result); with $("#label").val(result);
<input type="number" id="field1">
<input type="number" id="field2">
<input id="result"></input>
<script>
$("#download, #contention").keyup( function(){
var n1 = $("#download").val();
var n2 = $("#contention").val();
var result = n1/n2;
$("#result").val(result);
});
</script>
DEMO:
http://jsfiddle.net/A3qat/51/
If you textbox, then you can get the value of the textbox or you can set the value of the textbox using .val()
On your
HTML
<input type="number" id="field1">
<input type="number" id="field2">
<span><input type="text" id="label" ></span>
JS
$("#field1, #field2").keyup( function(){
var n1 = $("#field1").val();
var n2 = $("#field2").val();
var result = n2/n1;
$("#label").val(result);
});
I'm trying to get this thing work for a while but I guess I need to tweak the code from somewhere. I thought, someone here could better guide me instead of banging my head to my coding screen :)
here's the actual process:
<input type="hidden" name='oneSelectionChk_1'>
<input type="checkbox" name='awp_group_1' id='id1'>
<input type="checkbox" name='awp_group_1' id='id2'>
<input type="checkbox" name='awp_group_1' id='id3'>
<input type="checkbox" name='awp_group_1' id='id4'>
<input type="hidden" name='oneSelectionChk_2'>
<input type="checkbox" name='awp_group_2' id='id5'>
<input type="checkbox" name='awp_group_2' id='id6'>
<input type="checkbox" name='awp_group_2' id='id7'>
<input type="checkbox" name='awp_group_2' id='id8'>
<input type="hidden" name='oneSelectionChk_3'>
<input type="checkbox" name='awp_group_3' id='id9'>
<input type="checkbox" name='awp_group_3' id='id10'>
<input type="checkbox" name='awp_group_3' id='id11'>
<input type="checkbox" name='awp_group_3' id='id12'>
what I'm using for jQuery is:
var chkFields = $("input[name='oneSelectionChk']");
$.each(chkFields, function(i, field){
var groupID = field.id.split('_'); // Getting the ID of the group
var chkGroupBoxes = $('input[name="awp_group_"'+groupID[1]);
if(field.value==1)
{
//$.each(chkGroupBoxes, function(j, thisChkBox){
//alert(thisChkBox.value + " #"+j);
alert( $('input[name="awp_group_"'+groupID[1]).filter(':checked').length);
if($('input[name="awp_group_"'+groupID[1]+':checked').length > 0 )
{
//$.scrollTo( '#awp_container', 1200 );
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Selected ");
//alert( "Class AlertMsgText Should be removed Now");
$("#selectInstruction_"+groupID[1]).removeClass("AlertMsgText");
//return
}
else
{
alert($('input[name="awp_group_"'+groupID[1]+':checked').length+" Still not selected ");
//alert("Please select atleat 1 from Option #"+groupID[1]);
$("#selectInstruction_"+groupID[1]).addClass("AlertMsgText");
$.scrollTo( '#awp_container', 1200 );
//return;
}
//});
}
});
This code always giving me 0 length of checkboxes, I'm not sure if I need to loop through again for each checkbox or this might work?
Any quick help should be appreciated!
Try
var chkFields = $('input[name^="oneSelectionChk"]');
$.each(chkFields, function (i, field) {
var groupID = field.name.replace('oneSelectionChk_', '')
var chkGroupBoxes = $('input[name="awp_group_' + groupID + '"]');
if (chkGroupBoxes.filter(':checked').length == 0) {
alert('please select at least one checkbox under: ' + field.name)
}
});
Demo: Fiddle
There is no element with name attribute of oneSelectionChk in your markup, the hidden inputs have name attributes that start with oneSelectionChk, you have to use attribute starts with selector.
In case that elements are siblings you can select the target elements using .nextUntil() method:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]');
$hidden.each(function(){
var $chekboxes = $(this).nextUntil('input[type=hidden]'),
$checked = $checkboxes.filter(':checked'),
$unchecked = $chekboxes.not($checked);
});
Using name attributes:
var $hidden = $('input[type=hidden]').filter('[name^=oneSelectionChk]'),
$checkboxes = $('input[type=checkbox]');
$hidden.each(function() {
var n = this.name.split('_')[1];
var $grp = $checkboxes.filter('[name="awp_group_'+ n +'"]');
// ..
});
I have this html:
<input type="radio" name="r1" value="v1"><input name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2"><input name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1">
<textarea rows=6 cols=80 name="conclus" id="idConclus">
</textarea><br><br>
Is there a way on js to fill textarea with titles and values of inputs by selecting some of them and clicking a button?
e.g.: "text1 - value1, text2 - value2" etc.
thanks for material.
mmm... Felix King, in your examples the button updates the form. and if i need to put one testfield 1, then put some text in textarea manually, and then again textfield 2 and so on? i mean, without updating the textarea?
getElementById is your friend :-)
<script>
getValues = new function() {
var myTextArea = document.getElementById('idConclus');
var radio1 = document.getElementById('asd1');
var radio2 = document.getElementById('asd2');
myTextArea.value = radio1.title + ' - ' + radio1.value + ' ,'
+ radio2.title + ' - ' + radio2.value;
}
</script>
<input type="radio" name="r1" value="v1">
<input type="text" name="asd1" title="text1" id="asd1"><br>
<input type="radio" name="r2" value="v2">
<input type="text" name="asd2" title="text1" id="asd2"><br>
<input type="button" name="but1" handler = getValues>
I suggest you read about JavaScript and forms.
Assuming you have this HTML:
<form name="data">
<input name="asd1" title="text1" id="asd1"><br>
<input name="asd2" title="text2" id="asd2"><br>
<input type="button" name="but1" value="update">
<textarea rows=6 cols=80 name="conclus" id="idConclus"></textarea>
</form>
you can do this:
var inputs = ['asd1', 'asd2'];
var form = document.data;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
var input = form[inputs[i]];
text.push(input.title + " - " + input.value);
}
textarea.value = text.join(' ');
}, false);
See a live example here: http://jsfiddle.net/6kbtH/
Update:
If you want to control which values are put into the textbox, I would use checkboxes, give them the same name and the name of the input as value like so:
<input type="checkbox" name="take" value="asd1"><input name="asd1" title="text1" id="asd1">
<input type="checkbox" name="take" value="asd2"><input name="asd2" title="text2" id="asd2">
Then you can loop with nearly the same code over those values:
var form = document.data;
var inputs = form.take;
var button = form.but1;
var textarea = form.conclus;
button.addEventListener('click', function() {
var text = Array();
for(var i = 0, length = inputs.length; i < length; i++) {
if(inputs[i].checked) {
var input = form[inputs[i].value];
text.push(input.title + " - " + input.value);
}
}
textarea.value = text.join(' ');
}, false);
Live example: http://jsfiddle.net/sJdqb/
Note: You have to take care of cross-browser issues regarding attaching the event listener yourself if you don't use a JavaScript library. The examples I gave will work in Firefox and WebKit-based browsers.