Script is supposed to check all hidden checkboxes when the main checkbox attribute is checked as TRUE.
If it's left unchecked, or if user checks/unchecks, the same value should be applied for the hidden attributes.
It works fine 90% of times, but it seems in some cases (not sure how yet) it doesnt work, and some results come in where user has main checkbox as TRUE but all others as FALSE, and vice-versa.
Why does it happen?
<script>
$(function() {
var marketingMAIN= $("input[type='checkbox'][name='marketingMAIN']");
var marketingPhone = $("input[type='hidden'][name='marketingPhone']");
var marketingRobo = $("input[type='hidden'][name='marketingRobo']");
var marketingSMS = $("input[type='hidden'][name='marketingSMS']");
var marketingEmail = $("input[type='hidden'][name='marketingEmail']");
var marketingIM = $("input[type='hidden'][name='marketingIM']");
var marketingPush = $("input[type='hidden'][name='marketingPush']");
var marketingPaperMail = $("input[type='hidden'][name='marketingPaperMail']");
marketingMAIN.on('change', function()
{
if ($(this).val() == "TRUE") {
marketingPhone.prop('checked',true);
marketingPhone.val('TRUE');
marketingRobo.prop('checked',true);
marketingRobo.val('TRUE');
marketingSMS.prop('checked',true);
marketingSMS.val('TRUE');
marketingEmail.prop('checked',true);
marketingEmail.val('TRUE');
marketingIM.prop('checked',true);
marketingIM.val('TRUE');
marketingPush.prop('checked',true);
marketingPush.val('TRUE');
marketingPaperMail.prop('checked',true);
marketingPaperMail.val('TRUE');
} else {
marketingPhone.prop('checked',false);
marketingPhone.val('FALSE');
marketingRobo.prop('checked',false);
marketingRobo.val('FALSE');
marketingSMS.prop('checked',false);
marketingSMS.val('FALSE');
marketingEmail.prop('checked',false);
marketingEmail.val('FALSE');
marketingIM.prop('checked',false);
marketingIM.val('FALSE');
marketingPush.prop('checked',false);
marketingPush.val('FALSE');
marketingPaperMail.prop('checked',false);
marketingPaperMail.val('FALSE');
}
});
});
</script>
The hidden attributes are marked as follows:
<input type="hidden" name="marketingPhone" value=""/>
<input type="hidden" name="marketingRobo" value=""/>
<input type="hidden" name="marketingSMS" value=""/>
<input type="hidden" name="marketingEmail" value=""/>
<input type="hidden" name="marketingIM" value=""/>
<input type="hidden" name="marketingPush" value=""/>
<input type="hidden" name="marketingPaperMail" value=""/>
The value won't change for a checkbox unless you specifically change it. Try using is() like in this answer.
Instead of checking the visible checkbox's value in your change listener like this:
if ($(this).val() == "TRUE") {
Check its checked attribute:
if ($(this).is(":checked")) {
Here's a working example:
$(function() {
var marketingMAIN = $("input[type='checkbox'][name='marketingMAIN']");
var marketingPhone = $("input[name='marketingPhone']");
var marketingRobo = $("input[name='marketingRobo']");
var marketingSMS = $("input[type='hidden'][name='marketingSMS']");
var marketingEmail = $("input[type='hidden'][name='marketingEmail']");
var marketingIM = $("input[type='hidden'][name='marketingIM']");
var marketingPush = $("input[type='hidden'][name='marketingPush']");
var marketingPaperMail = $("input[type='hidden'][name='marketingPaperMail']");
marketingMAIN.on('change', function() {
if ($(this).is(":checked")) {
marketingPhone.prop('checked', true);
marketingPhone.val('TRUE');
marketingRobo.prop('checked', true);
marketingRobo.val('TRUE');
marketingSMS.prop('checked', true);
marketingSMS.val('TRUE');
marketingEmail.prop('checked', true);
marketingEmail.val('TRUE');
marketingIM.prop('checked', true);
marketingIM.val('TRUE');
marketingPush.prop('checked', true);
marketingPush.val('TRUE');
marketingPaperMail.prop('checked', true);
marketingPaperMail.val('TRUE');
} else {
marketingPhone.prop('checked', false);
marketingPhone.val('FALSE');
marketingRobo.prop('checked', false);
marketingRobo.val('FALSE');
marketingSMS.prop('checked', false);
marketingSMS.val('FALSE');
marketingEmail.prop('checked', false);
marketingEmail.val('FALSE');
marketingIM.prop('checked', false);
marketingIM.val('FALSE');
marketingPush.prop('checked', false);
marketingPush.val('FALSE');
marketingPaperMail.prop('checked', false);
marketingPaperMail.val('FALSE');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="marketingMAIN" value="" />
<input type="hidden" name="marketingPhone" value="" />
<input type="hidden" name="marketingRobo" value="" />
<input type="hidden" name="marketingSMS" value="" />
<input type="hidden" name="marketingEmail" value="" />
<input type="hidden" name="marketingIM" value="" />
<input type="hidden" name="marketingPush" value="" />
<input type="hidden" name="marketingPaperMail" value="" />
Change any of the checkboxes from type="hidden" to type="checkbox" and you can see them check and uncheck depending on what your main checkbox does.
Related
I want to update price on delete button click. When I am clicking on add button it adding the field and updating the price. But on delete button it is only deleting field and price is not updating.
$(document).ready(function() {
$('#add').on('click', function() {
var maxfld=$('.acmp').length;
var pricedl=500;
if(maxfld<10)
{
$('#new_ac').append('<div id="" class="acmp">'+(++maxfld)+' <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
}
if(maxfld>9)
{
alert("Cannot add more accompany");
}
var totalp=(pricedl*maxfld);
$('#amount').html(totalp);
});
$('#del').on('click', function() {
$('.acmp:last-child').remove();
var newp=totalp/maxfld;
$('.price').html(newp);
});
});
You are missing the below variables in delete block
var maxfld=$('.acmp').length;
var pricedl=500;
var totalp=(pricedl*maxfld);
May be the below code will work
$('#del').on('click', function() {
$('.acmp:last-child').remove();
var maxfld=$('.acmp').length;
var pricedl=500;
var totalp=(pricedl*maxfld);
var newp=totalp/maxfld;
$('.price').html(newp);
});
You need tot make your variables(totalp,maxfld) global. Now they are out of the scope of the second click function and it will return undefined. Your code should look like this:
$(document).ready(function() {
var maxfld = '';
var pricedl = '';
$('#add').on('click', function() {
maxfld = $('.acmp').length;
pricedl = 500;
if (maxfld < 10) {
$('#new_ac').append('<div id="" class="acmp">' + (++maxfld) + ' <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
}
if (maxfld > 9) {
alert("Cannot add more accompany");
}
var totalp = (pricedl * maxfld);
$('#amount').html(totalp);
});
$('#del').on('click', function() {
$('.acmp:last-child').remove();
var newp = totalp / maxfld;
$('.price').html(newp);
});
});
According to me you need to remove the element after you get the value of maxfld
$('#del').on('click', function() {
var pricedl=500,
maxfld=$('.acmp').length,
totalp=(pricedl*maxfld);
$('.acmp:last-child').remove();
var newp=totalp/maxfld;
$('.price').html(newp);
});
So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />
I am trying to submit values of a form through javascript it contains both text and two checkboxes.
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $(".relocation").val();
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation[]" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation[]" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
r_two.php
<?
$preffered_loc = $_POST['preffered_loc'];
$relocation = $_POST['relocation'];
?>
i am able to save the first value but i am not able to save relocation value, can anyone tell how i can save relocation. Important point here is that user can select both checkboxes also
The issue is that $relocation is picking only value yes even if i select 2nd selectbox. can anyone please correct my code
try this.
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $("#relocation").is(":checked");
var relyn = "";
if(relocation){
relyn = "Yes";
}else{
relyn = "No";
}
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relyn },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
alert("{ preffered_loc: "+preffered_loc+",relocation: "+relyn+" }");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" id="relocation" />
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
As Satpal said:
You don't need two checkbox, maybe you want a radio button, but one checkbox can be checked = yes, not checked = no. I removed one of them.
You don't have an ID relocation. I changed it.
With the jQuery is(":checked") you get a true or false so I parse it to a Yes or No, following your code.
Since its a checkbox and not a radio user can have multiple selections, for eg:
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="checkbox" name="relocation[]" class="relocation" value="Both" >
try using the :checked selector,
$( ".relocation:checked" ).each(function(i,v){
alert(v.value)
});
Demo here
I think you should use class for the check-boxes instead of id, because id must be unique for each field. You should try this:
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = '';
var sap = '';
$( ".relocation" ).each(function() {
if($( this ).is(':checked')){
relocation = relocation+''+sap+''+$( this ).val();
sap = ',';
}
});
alert(rel);
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
Here is a sample code for your reference
<form id="myForm" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone No:<input name="phone" id="phone" type="text" /><br />
Gender: <input name="gender" type="radio" value="male">Male
<input name="gender" type="radio" value="female">Female<br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
function SubmitFormData() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var gender = $("input[type=radio]:checked").val();
$.post("submit.php", { name: name, email: email, phone: phone, gender: gender },
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
You couldn't select the checkbox elements at all because you weren't including the [] in the selector. You can either escape the brackets as described in this SO Q/A or simply remove the brackets (the example code below does the latter)
I'd suggest using radio buttons as the user can immediately see what the options are. (Have a third option for both)
The code below uses checkboxes and puts all selected options into an array that gets passed along. This will allow the user to use both options
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = [];
$(".relocation:checked").each(function () {
relocation.push ($this.vak ();
}); // :checked is provided by jquery and will only select a checkbox/radio button that is checked
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
And don't forget to remove [] from the checkboxes class.
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = {};
$('.relocation').each(function(index) {
if ($(this).is(':checked')) {
relocation[index] = $(this).val();
}
});
relocation = JSON.stringify(relocation);
$.post("r_two.php", { preffered_loc: preffered_loc, relocation: relocation }, function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
Variable 'relocation' must be an object to contain multiple values, like you said a user can select both YES and NO. And change the checkbox class from relocation[] to relocation.
I am displaying some check boxes. The user can check a maximum of 4 boxes. I store the checked value in 4 textboxes.
My problem: How can I correctly store the "new" checked value when the user randomly unchecks one box and checks another?
I store values as follows: First checked into item_1, second checked into item_2, third checked into item_3 ... If the user unchecks the first checked box, for example, how can I store the value of the next box he or she checks into item_1? Please help.
Simplified code
<input type="checkbox" name="prodname_1" id="prodname_1"value="1"/>
<input type="checkbox" name="prodname_2" id="prodname_2"value="2"/>
<input type="checkbox" name="prodname_3" id="prodname_3"value="3"/>
.
.
<input type="checkbox" name="prodname_10" id="prodname_10"value="10"/>
<input type="text" name="item_0" id="item_0"value=""/>
<input type="text" name="item_1" id="item_1"value=""/>
<input type="text" name="item_2" id="item_2"value=""/>
<input type="text" name="item_3" id="item_3"value=""/>
$(document).ready(function (e)
{
counter=0;
$('input[id^="prodname_"]').change(function()
{
id = $(this).attr('id');
var arr = id.split('_');
valueChecked=$('#'+id).val();
if(this.checked)
{
if(counter==4)
{
alert('Allready checked 4 items');
this.checked=false;
return false;
}
$("#item_"+counter).val(valueChecked);
++counter;
}
});
});
Instead of retaining a counter, just count the number of checked boxes when the change occurs.
Revised to use the logic you intended (took a little while to figure that out) :)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/9/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var checkboxes = $('input[id ^= "prodname_"]').change(function () {
var id = $(this).attr('id');
var arr = id.split('_');
valueChecked = $(this).val();
// Count of checked checkboxes
var counter = checkboxes.filter(':checked').length;
if ($(this).is(':checked')) {
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
} else {
// Add to the first available slot
$items.filter(function(){return $(this).val() == ""}).first().val(valueChecked);
}
} else {
// Remove the matching value
$items.filter(function(){return $(this).val() == valueChecked;}).first().val('');
}
});
});
note: The "jQuery way" for changing checkboxes is to use prop('checked', booleanvalue) (also changed above)
V2 - If you don't want gaps:
This version is actually simpler as it just clears the items and fills them, in order, with any checked checkbox values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/13/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var $checkboxes = $('input[id ^= "prodname_"]').change(function () {
// Count of checked checkboxes
var counter = $checkboxes.filter(':checked').length;
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
}
// Clear all the items
$items.val('');
// Fill the items with the selected values
var item = 0;
$checkboxes.filter(':checked').each(function () {
$('#item_' + (item++)).val($(this).val());
});
});
});
Look at
$(document).ready(function(e) {
var counter = 0,
$items = $('input[name^="item_"]');
$('input[id^="prodname_"]').change(function() {
var id = this;
if (this.checked) {
if (counter == 4) {
this.checked = false;
return;
}
$("#item_" + counter).val(this.value).attr('data-value', this.value);
++counter;
} else {
var $item = $items.filter('[data-value="' + this.value + '"]');
var index = $items.index($item);
$items.slice(index, counter).each(function(i) {
var $n = $items.eq(index + i + 1);
$(this).val($n.val() || '').attr('data-value', $n.attr('data-value'));
});
counter--;
$("#item_" + counter).val('').removeAttr('data-value');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="prodname_1" id="prodname_1" value="1" />
<input type="checkbox" name="prodname_2" id="prodname_2" value="2" />
<input type="checkbox" name="prodname_3" id="prodname_3" value="3" />
<input type="checkbox" name="prodname_4" id="prodname_4" value="4" />
<input type="checkbox" name="prodname_5" id="prodname_5" value="5" />
<input type="checkbox" name="prodname_6" id="prodname_6" value="6" />
<input type="checkbox" name="prodname_7" id="prodname_7" value="7" />
<input type="checkbox" name="prodname_8" id="prodname_8" value="8" />
<input type="checkbox" name="prodname_9" id="prodname_9" value="9" />
<input type="checkbox" name="prodname_10" id="prodname_10" value="10" />
<input type="text" name="item_0" id="item_0" value="" />
<input type="text" name="item_1" id="item_1" value="" />
<input type="text" name="item_2" id="item_2" value="" />
<input type="text" name="item_3" id="item_3" value="" />
On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.