I try to change each hidden input value if checkbox is checked using jquery
I need to using for loop because html input field is generate by php loop from db too. so here is generated html code look like :
Html :
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="" type="hidden">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="" type="hidden">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="" type="hidden">
Jquery :
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = '#gift' + i;
var val = '#gift-true' + i;
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
but this code didn't work.
P.S :
code to generate html input is look like this :
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' id='gift$i' name='exm$i' value='1'> <br>
<input type='hidden' id='gift-true$i' value=''></td> <br><br>";
}
You can do this by using next() function as all the inputs are next to the checkbox. please replace var tot = 3; with var tot = <?php echo $tot; ?>; and type="text" with type="hidden"
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Changes this two value in your code
var chk = $('#gift' + i).val();
var val = $('#gift-true' + i).val();
This is what u want i guess
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Try this
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = $('#gift' + i);
var val = $('#gift-true' + i);
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
You need to get object instead of string right now you are getting a string which is '#gift' + i. Wrap it inside $('#gift' + i) to get the object.
Only relevant input should be set on change of a checkbox. You should not loop again for each input on change event.
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
// no need for another loop as you should target only relevant input field
$('input#gift-true' + i).val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
Yo do not need loop here. Just change the value of the next input.
$('input[type="checkbox"]').change(function(){
var $hidden = $(this).next('input[type="hidden"]');
if ($hidden.length) {
var checked = $(this).is(':checked');
if (checked) {
$hidden.val('yes');
} else {
$hidden.val('no');
}
}
});
//call function for every checkbox which are already on page
$('input[type="checkbox"]').change();
This code will work for every checkbox on the page. To avoid this just use stronger selector: $('.some-class input[type="checkbox"]')
My answer, similar to a few others, also eliminates the for loop.
jQuery(function ($) {
// do this if you do not know the state of the generated checkbox
$("input[type='checkbox']").each(function () {
$(this).next().val($(this).prop("checked") ? "yes" : "no");
});
// then this for your event handler
$("input[type='checkbox']").on("change", function (e) {
$(e.target).next().val($(e.target).prop("checked")?"yes":"no");
})
});
Change you id to class
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' class='gift' name='exm$i' value='1'> <br>
<input type='hidden' name='gift-exm$i' class='gift-true' value=''></td> <br><br>";
}
refactor your code as follows
$('.gift').change(function(e) {//remove any loops /keep the change event
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");//select the hidden input using next()
});
ps: don't forget to add a name to the hidden input
$('.gift').change(function(e) {
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
Related
I have a simple HTML form that is used for bookings. Once completed it submits the fields via e-mail which can then be automatically uploaded into my Access database with VBA.
The process works fine if there is just text in the form but I want to include radio button choices as well. The problem is that it doesn't include an indication as to which button has been chosen.
The body of the e-mail, if "text" was entered into the text box and choice2 was selected would be:
text
Choice1
Choice2
Choice3
What I would like it to be is:
text
Choice2.
Can this be done?
A simplified version of my code so far is:
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
str += elem[i].value + "\r\n";
}
}
return str;
}
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
You need to check if the element is checked.
And since you're adding it in the same loop as the text field you also need to make sure the element that has to be checked is actually a radio button:
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
But: In your snippet everything is added to the TO field of the mail, is that intended?
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
}
}
return str;
}
<html>
<head>
<title>Radio button trial</title>
</head>
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
</body>
</html>
I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>
So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.
It should display the total when the radio button 'yes' is clicked.
<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
count++;
alert(count);
}
}}
This should do the trick:
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
try this using jquery
Method 1:
alert($('.checkbox_class_here :checked').size());
Method 2:
alert($('input[name=checkbox_name]').attr('checked'));
Method: 3
alert($(":checkbox:checked").length);
Try this code
<br />Apples
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();" />
Javascript
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
alert(count);
}
}
}
FIDDLE DEMO
Thanks to Marlon Bernardes for this.
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
If you have more than one form with different checkbox names in each, the above code will count all checkboxes in all forms.
To get over this, you can modify it to isolate by name.
var le = document.querySelectorAll('input[name="chkboxes[]"]:checked').length;
The initial code was very nearly right. the line
alert(count);
was in the wrong place. It should have come after the second closing brace like this:-
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count);
}
In the wrong place it was giving you an alert message with every checked box.
var checkboxes = document.getElementsByName("fruit");
for(i = 0 ; i<checkboxes.length; i++)
{
if(checkboxes[i].checked==0){checkboxes.splice(i,1);}
}
alert("Number of checked checkboxes: "+checkboxes.length);
function checkboxes(){
var inputs = document.getElementsByTagName("input");
var inputObj;
var selectedCount = 0;
for(var count1 = 0;count1<inputs.length;count1++) {
inputObj = inputs[count1];
var type = inputObj.getAttribute("type");
if (type == 'checkbox' && inputObj.checked) {
selectedCount++;
}
}
alert(selectedCount);
}
<html>
<body>Fruits
<br />
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />Apple
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();"/>
</body>
</html>
Take a look at this:
<div id="main">
<div id="a">
<input value="1" />
<input value="2" />
<input value="3" />
</div>
<div id="b">
<input value="4" />
<input value="5" />
</div>
</div>
I need to get each input value inside div#a and each input value in div#b and build a matrix/mixing of those values, taking the same example as before, this is what the code should return:
<div id="mixed">
<input value="1" /><input value="4" />
<input value="1" /><input value="5" />
<input value="2" /><input value="4" />
<input value="2" /><input value="5" />
<input value="3" /><input value="4" />
<input value="3" /><input value="5" />
</div>
I have tried to move inside div#main using this code:
$("#main div").each(function() {
var that = $(this);
console.log("that.attr('id')");
});
But console.log() never logs something so I must doing something wrong. This is a advanced topic for me and need some help, any?
UPDATE
At this point I have this maded:
$("#choices div").each(function() {
var that = $(this);
that.each(function() {
var thati = $(this);
console.log(thati);
});
});
And I think in the second .each() is where I can get the input values and try to build the matrix
Should help:
var arr = [];
$('#a input').each(function () {
var that = $(this);
$('#b input').each(function () {
arr.push(that.val());
arr.push($(this).val());
});
});
Then go through the array and dynamically generate the HTML. You can treat this like a matrix by stepping every 2 values.
var a = $('#a input');
var b = $('#b input');
var html = '';
a.each(function () {
var first = this;
b.each(function () {
html += '<div>' + first.outerHTML + this.outerHTML + '</div>'
});
});
$('#mix').html(html);
jsFiddle here
update: code for what's asked for in comments.
var divs = $('#main > div');
var html = '';
divs.each(function (index) {
var divsLength = divs.length,
inputs = $('input', divs[index]),
inputsLength = inputs.length;
for (var i = 0; i < divsLength; i++) {
if (i === index) {
continue;
}
for (var j = 0; j < inputsLength; j++) {
$('input', divs[i]).each(function () {
html += inputs[j].outerHTML + this.outerHTML + '<br />';
});
}
}
});
$('#mix').html(html);
I have a group of check boxes with same name, what I need is when I click any one of them, other checkboxes must get disabled. how should I apply Javascript over it?
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
Please help...
You could do
$('input').attr('disabled',true);
...if you really need it. But you might be better off using radio buttons.
Try the demo
<script type="text/javascript">
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].checked !=true)
document.test.finallevelusers[i].disabled='true';
}
</script>
probably you want them enabled again when user uncheck the checkbox
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].disabled ==true)
document.test.finallevelusers[i].disabled='false';
}
<script type="text/javascript">
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}
</script>
</head>
<body>
<form name="aForm" action="">
<p>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
</p>
</form>
<script type="text/javascript">
disableHandler(document.forms.aForm, 'finallevelusers[]');
</script>
Hope This solution helps you-
your DOM could be something like this :
<div class="checkboxes">
<input type="checkbox" name="sameCheck" class="checkbox" id="1" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="2" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="3" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="4" onchange="checkChange()">
</div>
And your logic is this :
let checkbox = document.querySelectorAll('.checkbox')
let b = false;
function checkChange(){
b = !b
if(b){
for(let i = 0 ; i< checkbox.length; i++){
if(checkbox[i].checked === false){
checkbox[i].disabled = 'true';
}
}
}else{
for(let i = 0 ; i< checkbox.length; i++){
checkbox[i].removeAttribute('disabled');
}
}
}
Try code like this
<script>
function uncheck(){
for(var ii=1; ii<=4; ii++){
if(document.getElementById("q6_"+ii).checked==true){
document.getElementById("q6_"+ii).checked=false;
}
}
}
</script>