Select children elements based on class in iteration - javascript

Either using Vanilla Javascript or jQuery.
// html
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_1"> Bleeding puncture
<div data-target="patient_event_type_ids_1" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[blood_aspirated]" id="patient_blood_aspirated_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[blood_aspirated]" id="patient_blood_aspirated_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[iv_test]" id="patient_iv_test_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[iv_test]" id="patient_iv_test_negative"> Negative
</div>
</div>
<input type="checkbox" value="1" checked="checked" name="patient[event_type_ids][]" id="patient_event_type_ids_2"> Vascular puncture
<div data-target="patient_event_type_ids_2" class="form-sub">
<div class="form-group">
<input type="radio" value="true" name="patient[abc]" id="patient_abc_true"> Yes
<input type="radio" value="false" checked="checked" name="patient[abc]" id="patient_abc_false"> No
</div>
<div class="form-group">
<input type="radio" value="positive" name="patient[xyz]" id="patient_xyz_positive"> Positive
<input type="radio" value="negative" checked="checked" name="patient[xyz]" id="patient_xyz_negative"> Negative
</div>
</div>
// javascript
var subForms = $('.form-sub');
subForms.each(function() {
var subForm = this;
var parentForm = '#' + subForm.dataset.target;
if ($(parentForm).prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
$(parentForm).change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).hide();
$(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
}
});
});
I want to clear all input when the checkbox is unchecked. The line $(':input') is definitely, but that's where I should select the responding inputs which are the children of .form-sub. How do I do that in Javascript?

replace this line
var parentForm = '#' + subForm.dataset.target;
by
var parentForm = $( subForm ).prev();
and update the change event as
if ( parentForm.prop('checked')) {
$(subForm).show();
} else {
$(subForm).hide();
}
parentForm.change(function(){
if($(this).prop("checked")) {
$(subForm).show();
} else {
$(subForm).find(':input')
.not(':button, :submit, :reset, :hidden')
.removeAttr('checked')
.removeAttr('selected')
.not(':checkbox, :radio, select')
.val('');
$(subForm).hide();
}
});

Related

jQuery form submit button goes to URL based on checkbox selected

I have a simple contact form with multiple checkboxes, when a user selects a checkbox it should go to the url/folder tied to the url that's in the value. The current problem is after a user checks the checkbox and clicks submit, then goes back to that page and the checkbox resets, the submit button still takes them to the previously selected checkbox.
Need a way to fully reset the form and disable the button so the submission doesn't get too confusing for the user. Thanks!
Here is my form code:
<form name="frm" id="myForm" method="post" >
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" onclick="formaction(this)"/>
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" onclick="formaction(this)"/>
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" onclick="formaction(this)"/>
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>
Here is the script:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
});
$('[data-toggle="btns"] .btn').on('click', function(){
var $this = $(this);
$this.parent().find('.active').removeClass('active');
$this.addClass('active');
});
$('.selectme input:checkbox').click(function() {
$('.selectme input:checkbox').not(this).prop('checked', false);
});
$('.provider-checkboxes input:checkbox').click(function() {
$('.provider-checkboxes input:checkbox').not(this).prop('checked', false);
});
function formaction(checkbox){
document.getElementById("myForm").action = checkbox.value;;
}
function UncheckAll(){
var w = document.getElementsByTagName('input');
for(var i = 0; i < w.length; i++){
if(w[i].type=='checkbox'){
w[i].checked = false;
}
}
}
Consider the following code. Think this will help, based on what you have shared.
$(function() {
function setFormAction(frm, a) {
frm.attr("action", a);
}
function unCheckAll() {
$("input[type='checkbox']").prop("checked", false);
$(".provider-checkboxes .btn").hide();
}
$('.provider-checkboxes input:checkbox').click(function() {
unCheckAll();
$(this).prop("checked", true);
$(".provider-checkboxes .btn").toggle(300);
setFormAction($("#myForm"), "./" + $(this).val());
console.log($("#myForm")[0]);
});
unCheckAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="frm" id="myForm" method="post">
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" />
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" />
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" />
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>

How to enable disable sup tag in javascript

i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.
my view:
<label>code<sup id="star" disabled>*</sup></label>
>Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
> id="no"/>onchange="starenable()"/>no
my javascript:
function starenable() {
if (document.getElementById('yes').checked) {
document.getElementById("star").disabled = false;
} else if (document.getElementById('no').checked) {
document.getElementById("star").disabled = true;
}
}
i tried this but no change in view. any ideas?
Here is your solution https://jsfiddle.net/me9uwL2d/
<input type="radio" name="test" value="Yes" />Yes
<input type="radio" name="test" value="No" />No
<input type="text" />
$('input[type="radio"]').change(function() {
if( $(this).is(':checked') && ($(this).attr('value') == 'Yes')) {
$('input[type="text"]').val("*");
}else{
$('input[type="text"]').val('');
}
});
Input have disable attribute .Change the sub with input .And align the html code on proper format.Then add the * depend on checked radio button
Updated
note: sub tag not have a disable attribute
function starenable() {
if (document.getElementById('yes').checked) {
document.getElementById("star").disabled = false;
} else if (document.getElementById('no').checked) {
document.getElementById("star").disabled = true;
}
document.getElementById("star").innerHTML = document.getElementById('yes').checked ? '*' : '';
}
<label>code <sub id="star"></sub></label> Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()" />yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no
$(document).ready(function() {
$('input[type=radio][name=yes]').change(function() {
if (this.id == 'yes') {
$('#star').hide();
}
else if (this.id == 'no') {
$('#star').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>code<span id="star" >*</span></label>
Add to electronic
<input type="radio" name="yes" id="yes"/>yes
<input type="radio" name="yes"
id="no"/>no
use this
<label>code<sup id="star" style="visibility:hidden">*</sup></label>
Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()"/>yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no
function starenable() {
if (document.getElementById('yes').checked)
document.getElementById("star").style.visibility = "visible";
else if (document.getElementById('no').checked)
document.getElementById("star").style.visibility = "hidden";
}

Label -> Checkbox Text

I have this problem..
I have this HTML code for 2 groups of checkbox:
<label class="checkbox"><input type="checkbox" onClick="toggle_colors(this)" checked><i></i>All Colors</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox"><input type="checkbox" onClick="toggle_brands(this)" checked><i></i>Tutte le Marche</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Asus</label>
And I use this javascripts for select all/toggle all:
function toggle_brands(source) {
checkboxes = document.getElementsByName('brand');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function toggle_colors(source) {
checkboxes = document.getElementsByName('colore');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
When the user click on the checkbox I need to know if the checkbox is selected or not, to send the details of the query by AJAX..
To know if the checkbox I use this javascript:
$( "[type=checkbox]" ).change(function() {
if(this.checked) {
alert('checked');
}
else {
alert('unchecked');
}
});
I want the text at the right of the selected checkbox..!
Ok.. With the parent work fine!
I have added this code to create the query:
function create_query(){
var query = "SELECT * FROM computers ORDER BY " + ($("#ordine option:selected").val()) + " LIMIT " + ($("#risultati option:selected").val());
$.ajax({
type: "POST",
url: "static/cerca_prodotti.php",
data: "query="+query,
dataType: "html",
success: function(risposta){
$("div#risultati").html(risposta);
},
})
}
$( "[type=checkbox]" ).change(function() {
if(this.checked) {}
else {}
});
$("#ordine").change(function() {
create_query();
});
But I need to modify the query when the checkbox was checked/unchecked!
When you change the checked property programatically, the change event will not get triggered, you need to trigger the event manually.
$('input[data-all-type]').change(function() {
$('input[name="' + $(this).data('allType') + '"]')[this.checked ? 'not' : 'filter'](':checked').prop('checked', this.checked).change();
})
$("input[type=checkbox]:not([data-all-type])").change(function() {
if (this.checked) {
console.log('checked', this);
} else {
console.log('unchecked', this);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" name="color-all" data-all-type="colore"><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" name="brand-all" data-all-type="brand"><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Asus</label>
You can do that with only one function
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', $(source).is(':checked'))
//OR
$('input[name="' + things + '"]').prop('checked', source.checked);
}
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', source.checked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'colore')" checked><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'brand')" checked><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Asus</label>
You can get text of the parent node of the checkbox in this way:
$( "[type=checkbox]" ).change(function() {
var text = this.parentElement.innerText;
if(this.checked) {
alert(text + ': checked');
}
else {
alert(text + ': unchecked');
}
});

All / none checkbox

Why doesn't this "All / none" option do his job? I can't see why .attr('checked', status); doesn't toggle all the checkboxes.
And what's the most clever way to hide / show elements of #main belonging to selected categories?
$('input[name="all"]').click(function() {
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').attr('checked', status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>
Use .prop() not .attr()
See http://api.jquery.com/prop/
$('input[name="all"]').click(function(){ var status = $(this).is(':checked'); alert(status); $('input[type="checkbox"]').prop('checked', status); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>
As mentioned here, you should make use of jQuery's .prop() function for checking/unchecking checkbox elements.
So try to change your handler like so:
$('input[name="all"]').click(function(){
var status = !!$(this).prop('checked');
alert(status);
$('input[type="checkbox"]').prop('checked', status);
});
To hide/show elements, I recommend iterating over each one:
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('name');
var status = !!$(this).prop('checked');
if (status) {
$('#main').find('.' + name).show();
} else {
$('#main').find('.' + name).hide();
}
});
Regarding your last question for coloring, I'd recommend using a class, say for example gray.
var total = $('input[type="checkbox"]').not('[name=all]').length;
var count = $('input[type="checkbox"]:checked').not('[name=all]').length;
if (count === total) {
$('input[name="all"]').removeClass('gray');
} else {
$('input[name="all"]').addClass('gray');
}
This sets the checkboxes and the div visibility as needed.
It uses opacity to simulate a grayed-out checkbox.
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
$('[name="all"]').click(function() { //set all checkboxes to match All / none
$(':checkbox')
.prop('checked', this.checked)
.change();
});
$('input')
.change(function() { //show divs corresponding to checked input
var checked= $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name)
.toggle(this.checked);
$('[name="all"]')
.prop('checked', checked > 0)
.toggleClass('someChecked', checked && checked<$(':checkbox:not([name="all"])').length);
})
.change(); //run the method immediately
.someChecked {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label>
<input type="checkbox" name="all" checked="true">
All / none
</label>
<label>
<input type="checkbox" name="cat1" checked="true">
A
</label>
<label>
<input type="checkbox" name="cat2">
B
</label>
<label>
<input type="checkbox" name="cat3">
C
</label>
<label>
<input type="checkbox" name="cat4">
D
</label>
// Bind also the single checkboxes to show/hide the elements in div
$('input[type = "checkbox"]').click(function(){
if($(this).prop('checked'))
$('div.' + $(this).attr('name')).show();
else
$('div.' + $(this).attr('name')).hide();
});
$('input[name="all"]').click(function(){
var status = $(this).is(':checked');
alert(status);
$('input[type="checkbox"]').each(function(){
$(this).prop('checked', status);
if(!status)
$('div.' + $(this).attr('name')).hide();
else
$('div.' + $(this).attr('name')).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked="true">All / none</label>
<label><input type="checkbox" name="cat1" checked="true">A</label>
<label><input type="checkbox" name="cat2">B</label>
<label><input type="checkbox" name="cat3">C</label>
<label><input type="checkbox" name="cat4">D</label>
All answers here were great. Just for future reference, I post the one I'll use (which is a mix of #RickHitchcock's and the usage of indeterminate state of a checkbox) :
$('input[name="all"]').click(function() { $(':checkbox').prop('checked', this.checked).change(); });
$('input[type="checkbox"]').change(function() {
var checked = $(':checkbox:not([name="all"]):checked').length;
$('div.' + this.name).toggle(this.checked);
$('input[name="all"]').prop('checked', checked > 0)
.prop('indeterminate', checked && checked < $(':checkbox:not([name="all"])').length);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
<div class="cat1">Element of category1</div>
<div class="cat4">Element of category4</div>
<div class="cat3">Element of category3</div>
<div class="cat1">Element of category1</div>
<div class="cat2">Element of category2</div>
</div>
<label><input type="checkbox" name="all" checked>All / none</label>
<label><input type="checkbox" name="cat1" checked>A</label>
<label><input type="checkbox" name="cat2" checked>B</label>
<label><input type="checkbox" name="cat3" checked>C</label>
<label><input type="checkbox" name="cat4" checked>D</label>

Validation for dynamic radio button,checkbox and text area

I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>

Categories

Resources