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.
Related
Could anybody help me with this problem? I have an input price value that changes when you select different checkboxes, but it doesn't add up.
I don't really know how to fix it that if you select something, it adds to the total price, and when you select another one it adds again.
The foreach is to get all the exa_names from the Extra table with the checkbox and the price from that item.
Javascript
$(document).ready(function(){
$(".option").change(function(){
var id = $(this).attr('id');
console.log(id);
var id_number = id.split("_")[1];
console.log(id_number);
var hidden_input = $(".option_price" + id_number).val();
console.log(hidden_input);
})
});
HTML
<label>Options</label><br>
#foreach($options as $option)
<div>
<input type="checkbox" class="option" id="option_{{ $option->exa_id }}" name="option_{{ $option->exa_id }}" value="{{ $option->exa_id }}" {{ isset($cache) ? (isset($cache['option_' . $option->exa_id]) ? 'checked' : '') : (old() ? (old('option_' . $option->exa_id) ? 'checked' : '') : ($inschrijving ? (in_array($registration->exa_id, $registration_options) ? 'checked' : '') : '')) }} >
<input type="hidden" value="{{ $option->exa_price}}" class="option_price_{{ $option->exa_id }}">
<label>{{ $option->exa_name }}</label>
<label> €{{ $option->exa_price }} </label>
</div>
#endforeach
Html input totalprice(where it has to show the total price)
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label>Total</label>
<input type="text" name="totalprice" id="totalprice" class="form-control" data-blocked="<>{}" value="0" required>
</div>
</div>
</div>
RegistrationController
$options_ids_array = array();
$options = Extra::all();
foreach($options as $option){
$option->exa_id = "option_" . $option->exa_id;
$input_option = $option->exa_id;
if(!is_null($input_option)){
$options_ids_array[] = $input_option;
}
}
$registration->dev_option_id = implode(",", $options_ids_array);
$registration->save();
I think it's better to store the price of your item in a javascript variable (because it prevent to change the value of hidden input and have easy access on js side) and access to your price through your checkbox value (because it is exactly the id you tried to get with id value by split it with _ character). For add price from checked checkboxes (if they are not too much checkboxes), create a check function to detect which of them are checked and then select the price of each and add them to each other, then put it to your price place. Something like:
var options = $(".option");
var options_price = ['your', 'price', 'values', 'according', 'to', 'options', 'id'];
function optionsPrice() {
var total_price = 0;
options.each(function () {
var option = $(this);
if (option.is(':checked') && option.val() != '' && $.inArray(option.val(), Object.keys(options_price))) {
total_price += options_price[option.val()];
}
});
return total_price;
}
Call optionsPrice function on any checkbox change.
OR if you have a lot of checkeboxes on your page,
you can have a global total price variable and add or sub price from it on any checkbox change. Something like:
var total_price = 0;
var options = $(".option");
var options_price = ['your', 'price', 'values', 'according', 'to', 'options', 'id'];
var option, val;
options.on('change', function() {
option = $(this);
val = option.val();
if(val && val != '' && $.inArray(val, Object.keys(options_price)) !== -1) {
if(option.is(':checked')) {
total_price += options_price[option.val()];
} else {
if(total_price > 0) {
total_price -= options_price[option.val()];
} else {
total_price = 0;
}
}
}
});
I hope it helps :)
You've got the tricky part - uniquely identifying your inputs in JS - already done. All that is left is to sum them up!
The simplest option is to iterate over all your inputs whenever one of them changes, and recalculate the price from scratch.
I'm not 100% sure how your inputs and prices and extra costs work, but let's make it simple. Here's some example HTML in the format your Blade template could generate:
<div>
<input type="checkbox" class="option" id="option_1" name="option_1" value="1" checked>
<input type="hidden" value="1" class="option_price_1">
<label>Orange</label>
<label>1</label>
</div>
<div>
<input type="checkbox" class="option" id="option_2" name="option_2" value="2">
<input type="hidden" value="2" class="option_price_2">
<label>Apple</label>
<label>2</label>
</div>
<div>
<input type="checkbox" class="option" id="option_3" name="option_3" value="3" checked>
<input type="hidden" value="3" class="option_price_3">
<label>Pear</label>
<label>3</label>
</div>
<!-- I've added a total area to display the total result -->
<div id="total"></div>
Now taking your code, and using jQuery's .each() to iterate over all inputs on the page:
$('.option').change(function() {
// This is what we'll use to sum the prices
var total = 0;
// Use .each() to iterate over all .option inputs
$('.option').each(function(index) {
// Inside .each, $(this) represents the current element
var id = $(this).attr('id');
var id_number = id.split("_")[1];
// Note your code was missing the _ after price here
var hidden_input = $(".option_price_" + id_number).val();
// Is this option checked? If yes, we want to add its value to
// the total
if ($(this).prop('checked')) {
// .val() returns a string, prefixing hidden_input with '+' is
// a trick to cast it as a number
total += +hidden_input;
}
console.log(id, id_number, hidden_input, total);
});
// We've processed all inputs and have a total, update our page with
// the result
$('#total').html(total);
});
Done!
The above works fine, but here are some suggestions for minor improvements:
1) Use for on your labels, so that clicking on the text will also toggle the checkbox.
2) It is good practice to cache your jQuery selectors, otherwise jQuery has to parse the DOM each time to look for them. That's trivially unimportant in this example, but it is good practice to get into so you won't get bitten by problems as your pages get more complex.
3) It is good practice to separate your JS code into smaller chunks, so eg have a function that sums up the price, and a separate event handler which simply calls that when an option is changed.
Putting all that together, here's updated code:
<!-- Just one for example -->
<div>
<input type="checkbox" class="option" id="option_1" name="option_1" value="1" checked>
<input type="hidden" value="1" class="option_price_1">
<label for="option_1">Orange</label>
<label>1</label>
</div>
And now the JS:
// Cache your selectors
var $options = $('.option'),
$total = $('#total');
// Event handler, with callable function
$options.on('change', sumInputs);
function sumInputs() {
var id, id_number, hidden_input, price = 0;
$options.each(function(index) {
id = $(this).attr('id');
id_number = id.split("_")[1];
hidden_input = $(".option_price_" + id_number).val();
if ($(this).prop('checked')) {
price += +hidden_input;
}
console.log(id, id_number, hidden_input, price);
});
$total.html(price);
}
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);
});
});
This is my html output.
When user click on + (Add Tab) icon then how to check previos fields are filled or not
If any fields is empty then a error message will come.
jQuery('.add-contact').click(function (e) {
e.preventDefault();
// check previous box is field or not
{check code}
var siteUrl = jQuery(this).data('url');
var productId = jQuery(this).data('id');
var id = jQuery(".nav-tabs").children().length; //think about it ;)
var tabId = 'personalize_' + id;
jQuery(this).closest('li').before('<li>Personalize <span> x </span></li>');
var DataPersionalize = '<div class="tab-pane" id="' + tabId + '">';
DataPersionalize += '</div>';
// append data
jQuery('.tab-content').append(DataPersionalize);
jQuery('.nav-tabs li:nth-child(' + id + ') a').click();
});
How it is possible in case of radio button.
Thank
You could create an if else statement with all of the items in the original conditional separated by && and check if each of your input fields has a value with a length > 0 and for the radio button do $('.radio_button').is(':checked')) If they all pass then you can open the tab. If they don't pass you can $('.error-div').html("<div>Error Message</div>")
In case your radiobuttons all are in a group called ring and only one is selectable:
var isChecked = false,
radios = document.getElementsByName("ring");
for(radio in radios) {
isChecked = radios[radio].checked || isChecked;
}
console.log(isChecked);
HTML:
<input type="radio" id="ring1" name="ring">
<input type="radio" id="ring2" name="ring">
In case more than one are selectable, the same solution is usable, as long as you get the collection of required in the variable radios, lets say, id you use a class rings:
var radios = document.getElementsByClassName("rings");
HTML:
<input type="radio" id="ring1" class="rings">
<input type="radio" id="ring2" class="rings">
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 +'"]');
// ..
});
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);
});