How to capture whether a checkbox has been checked or not? - javascript

I have a Bootstrap form modal being used for a webinar signup. I've removed the other fields, but I have multiple text fields that are being captured and pushed to a CMS.
It's just these 3 checkboxes that I can't seem to get to push data across correctly. The checkboxes are recording all as "on" if the form is submitted once, but if the form is submitted a second time then the checkboxes that are checked/not checked will push through "on" and "off" accordingly. So it works on the second submit, but not on the first. Any help would be greatly appreciated. I'm new to javascript and jquery, so i'm now at the point of guessing.
$(document).ready(function() {
$('.register-webinar').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must select at least one session.");
return false;
}
});
$('input.webinar').change(function() {
if ($(this).is(":checked")) {
$(this).val("on")
} else {
$(this).val("off")
}
});
$('#railway_form').on("submit", function(e) {
e.preventDefault();
setTimeout(AoProcessForm(this), 200);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<div class="form-popup-bg">
<div class="form-container">
<button id="btnCloseForm" class="close-button">X</button>
<h1 style="text-align:center;">Register your attendance</h1>
<p style="text-align:center;">Please select which session/s you wish to attend.</p>
<form name="railway_webinar" id="railway_form" class="railway_webinar" action="">
<div class="form-group">
<input type="checkbox" id="Webinar_1" name="Webinar_1" class="webinar">
<label for="Webinar_1">webinar 1</label><br/>
<input type="checkbox" id="Webinar_2" name="Webinar_2" class="webinar">
<label for="Webinar_2">webinar 2</label><br/>
<input type="checkbox" id="Webinar_3" name="Webinar_3" class="webinar">
<label for="Webinar_3">webinar 3</label>
</div>
<input type="submit" value="Reserve my seat!" class="form-block-cta register-webinar" />
</form>
</div>
</div>

Figured it out. All I needed to do was set the checkbox value to "off", as they would all be "on" by default.

Related

How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked

I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit.
This is my JS:
function checkBoxes() {
$(' input[type=checkbox]').
attr('disabled', true);
$(document).on('click',
'input[type=checkbox]',
function (event) {
if ($(this).is(":checked")) {
console.log("1")
} else {
console.log('2')
}
});
}
The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django:
<div style="height:30px"></div>
<form method="post">
{% csrf_token %}
{{ context.form.as_p }}
<button type="submit">Submit</button>
</form>
How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again?
Just use
:checked and :not(:checked) in your jquery selector, like this:
$(document).on('click', 'input[type=checkbox]', function(event) {
if ($('.checkbox-container input[type=checkbox]:checked').length >= 3) {
$('.checkbox-container input[type=checkbox]:not(:checked)').attr('disabled', true);
} else($('.checkbox-container input[type=checkbox]').attr('disabled', false));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div class="checkbox-container">
<input type="checkbox" id="scales1" name="scales1" checked>
<input type="checkbox" id="scales2" name="scales2" checked>
<input type="checkbox" id="scales3" name="scales3">
<input type="checkbox" id="horns1" name="horns1">
<input type="checkbox" id="horns2" name="horns2">
<input type="checkbox" id="horns3" name="horns3">
</div>
</body>
</html>

DirtyForms does not work on input hidden field

I added dirtyForms to my forms to detect any changes on one of the input fields https://github.com/snikch/jquery.dirtyforms
HTML
<form>
<input type="text" id="post" name="post">
<input type="hidden" id="body" name="body">
<froala-editor input="body">
</froala-editor>
</form>
Javascript
$('document').ready(function() {
$('form').dirtyForms();
});
However for input hidden seems like it doesn't add the dirty class, it only works for input type="text" . Any ideas on how to solve this problem?
Because it does not make sense when the user is not the one entering the data in the field.
You can do it yourself
SO does not allow the editor so I tested here
$('form').toggleClass('mydirty', e.target.textContent !== "");
tests the editor, it makes more sense than the input field
https://plungjan.name/SO/froala/
$('form').dirtyForms({
helpers: [{
isDirty: function($node, index) {
if ($node.is('form')) {
return $node.hasClass('mydirty');
}
}
}]
});
var editor = new FroalaEditor('#froala')
$(document).on("keyup", function(e) {
$('form').toggleClass('mydirty', e.target.textContent !== "");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/froala-editor#3.2.3/js/froala_editor.min.js"></script>
<form>
<input type="text" id="post" name="post">
<input type="hidden" id="body" name="body">
<div id="froala" input="body">
</div>
</form>

How to align checkboxes horizontally next to each other and show form upon click?

i have been searching stackoverflow but, I am unable to find a solution pertaining to my problem. What i want is when a user clicks a checkbox, a form shows up. I managed to get one checkbox and make the form show up, but having trouble putting checkboxes side by side next to each other. So what i want is:
[] residential [] commercial [] industrial.
When a user clicks the above boxes, a form opens up on the same page. My code:
edit: Thanks to #brk for the solution. After copying the solution below, for some reason When i click on 'residential', i don't see anything popping up. My code:
<script>
// Add event listener to each of the radio button
document.querySelectorAll('input[name="selectType"]').forEach(function(item) {
item.addEventListener('click', function(e) {
// get the data-type from this, this data-type will be used to
// hide show relevant form
let name = this.getAttribute('data-type');
// hide previously displayed form
if (document.querySelector('.formDisplay') !== null) {
document.querySelector('.formDisplay').classList.remove('formDisplay');
}
// find the form whose name+_info is same as the name of the form
// & add a formDisplay to it
document.querySelector('form[name="' + name + '_info"]').classList.add('formDisplay');
})
})
</script>
<style>
form {
display: none;
}
.formDisplay {
display: block;
}
</style>
<html>
<body>
<div class="form-group">
<input id="checkboxR" data-type='res' name='selectType' type='radio'>
<label for="checkboxR">Residential</label>
<input id="checkboxC" data-type='com' name='selectType' type='radio'>
<label for="checkboxC">Commercial</label>
<input id="checkboxI" data-type='ind' name='selectType' type='radio'>
<label for="checkboxI">Industrail</label>
</div>
<form name="res_info" action="/result/" method="get" class="form-horizontal" role="form">
Residential Form
</form>
<form name="com_info" action="/result/" method="get" class="form-horizontal" role="form">
Commercial Form
</form>
<form name="ind_info" action="/result/" method="get" class="form-horizontal" role="form">
Industrial Form
</form>
</body>
</html>
So, I see 3 radio buttons, but clicking on them doesn't open up anything. Sorry im kinda new to html/css so this concept is new.
Make changes in your html and add another attribute data-type .This value will be used to display corresponding form.
Create tep css and initially hide all the forms. Add another class to display the form using display:block
Onclick of the radio button get the data-type find the forma whose name matches with this data-type and display that form
// Add event listener to each of the radio button
document.querySelectorAll('input[name="selectType"]').forEach(function(item) {
item.addEventListener('click', function(e) {
// get the data-type from this, this data-type will be used to
// hide show relevant form
let name = this.getAttribute('data-type');
// hide previously displayed form
if (document.querySelector('.formDisplay') !== null) {
document.querySelector('.formDisplay').classList.remove('formDisplay');
}
// find the form whose name+_info is same as the name of the form
// & add a formDisplay to it
document.querySelector('form[name="' + name + '_info"]').classList.add('formDisplay');
})
})
form {
display: none;
}
.formDisplay {
display: block;
}
<body>
<div class="form-group">
<input id="checkboxR" data-type='res' name='selectType' type='radio'>
<label for="checkboxR">Residential</label>
<input id="checkboxC" data-type='com' name='selectType' type='radio'>
<label for="checkboxC">Commercial</label>
<input id="checkboxI" data-type='ind' name='selectType' type='radio'>
<label for="checkboxI">Industrail</label>
</div>
<form name="res_info" action="/result/" method="get" class="form-horizontal" role="form">
Residential Form
</form>
<form name="com_info" action="/result/" method="get" class="form-horizontal" role="form">
Commercial Form
</form>
<form name="ind_info" action="/result/" method="get" class="form-horizontal" role="form">
Industrial Form
</form>
</body>
This worked for me
<body>
<div class="form-group">
<div class="horizontal">
<input id="checkbox" type=checkbox> Residential</input>
</div>
<div class="horizontal" id="delivery_div" style="display:none">
<input id="delivery" type=checkbox > etc </input>
</div>
</div>
<script>
var checkbox = document.getElementById('checkbox');
var delivery_div = document.getElementById('delivery_div');
checkbox.onclick = function() {
console.log(this);
if(this.checked) {
delivery_div.style['display'] = 'block';
} else {
delivery_div.style['display'] = 'none';
}
};
</script>
<style>
<body>
<div class="form-group">
<div class="horizontal">
<input id="checkbox" type=checkbox> Residential</input>
</div>
<div class="horizontal" id="delivery_div" style="display:none">
<input id="delivery" type=checkbox > etc </input>
</div>
</div>
<script>
var checkbox = document.getElementById('checkbox');
var delivery_div = document.getElementById('delivery_div');
checkbox.onclick = function() {
console.log(this);
if(this.checked) {
delivery_div.style['display'] = 'block';
} else {
delivery_div.style['display'] = 'none';
}
};
</script>
<style>
.horizontal {
display: inline-block;
float:left;
}
</style>
</body>
.horizontal {
display: inline-block;
float:left;
}
</style>
</body>

Materializecss - prop radio checkbox with jQuery on click

I have 1 radio item, and I want it to behave like a checkbox. So now, it gets selected but I couldn't bind it to prop state on click.
So I want to achieve is: when clicked on radio btn, it reverses its checked state.
Here is what I tried:
<form action="#">
<p>
<input name="group" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>
$(document).ready(function() {
$('#test').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
})
What interesting is, if I create another button and bind it to change checked value, it works
<button id="faker" type="button">
Faker Btn
</button>
$('#faker').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
Here is a fiddle: https://jsfiddle.net/55L52yww/81/
A radio can behave like a checkbox if you add a state attribute to the radio element like in:
<input name="group" type="radio" id="test" data-state="false"/>
Now, you can save the last state and compare with the current value in order to decide the action to do.
The snippet:
$('#test').on('click', function(e) {
var a = $(this).data('state');
var b = $(this).prop('checked');
if (a && b) {
b = false;
$(this).prop('checked', b);
}
$(this).data('state', b);
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group" type="radio" id="test" data-state="false"/>
<label for="test">Red</label>
</p>
</form>
When you get into the function that was triggered by the radio button itself, the state of the checked property has already changed. That causes a problem on the first click, because the new state is true and therefore your function sets it back to false.
You can solve this by keeping track of the checked state yourself in a separate data attribute and checking that instead.
$(function() {
$('#test').click(function() {
var $this = $(this);
if ($this.data('previousState')) {
$this.prop('checked',false).data('previousState',false);
}
else {
$this.prop('checked',true).data('previousState',true);
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group1" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>

Returning property on box unchecked

Trying to return form controls property to "enabled" if a checkbox is unchecked.
So, for this HTML piece:
<div id="post">
<div class="Response">
<label><input type="radio" name="Radio402" value="Y" id="R402Y" onchange='radioChange(this, "402")'>Yes</label>
</div>
<div class="responseDetails">
<div class="Observation">
<label for="Obs402">Observation:</label>
<textarea name="observation" id="Obs402" rows="6" disabled></textarea>
</div>
<div class="DueDate">
<label for="DueDate402">Due date:<br></label>
<input name="DueDate" class="DueDate_in" type="text" id="DueDate402"/>
</div>
<div class="actions">
<label for="pa402">Actions required to correct and/or prevent this observation:</label>
<textarea name="actions" id="pa402" rows="6"></textarea>
</div>?
</div>
</div>
<label for="item">Check me</label>
<input type="checkbox" id="item"/>
I am applying this JS
$(document).ready(function()
{
if($("#item").click(function()
{
$("#post").prop("disabled", true);
}));
else
{
$("#post").prop("disabled", false);
};
});
also tried that
$("#item").change(function(){
if (this.checked) {
$("#post").prop("disabled", true);
} else {
$("#post").prop("disabled", false);
}
});
It gets disabled if CHECKED, but if UNCHECKED it REMAINS disabled. What am I doing wrong? I also tried change(function)(). I got the feeling that JS does not see unchecking event and therefore does not return the property. Thanks in advance.
UPDATE: Oh guys, forgott to mention, there is textarea element that by default stays DISABLED and is controlled by a radiobtn elsewhere. This textfield shall NOT get ENABLED when box is unchecked.
You want to use :checked
$('#item').on('click', function(){
$("#post").prop("disabled", $(this).is(':checked'));
});
Example: http://jsfiddle.net/VTtw5/
You need to have the condition checking whether the check box is checked or not inside the change handler(prefer change event to click event) of the element. Then you need to enable/disable the input elements inside the #post element
jQuery(function ($) {
//change event handler
$("#item").change(function () {
//disable/enable input elements
$("#post :input").prop("disabled", !this.checked);
}).change();//set the initial state based on checked state of the checkbox
});
Demo: Fiddle

Categories

Resources