I know this is a repeated question, but I cannot make it run. I tried all the solutions I found here in SO and googling...
I have this radio button form in my page. What I want is that when the user selects the 'only one attendee' option a text field appears ONLY for this option. If the user selects another one it dissapears.
Once the user selects only one option, the text box appears.
I've been trying doing with javascript. I use this piece of code
<script>
$(document).ready(function()
$("#send_to_one").hide();
$("input:radio[name="people"]").change(function(){
if(this.checked){
if(this.value =='one'){
$("#send_to_one").show()
}else{
$("#send_to_one").hide();
}
}
}
});
</script>
The form's code is
<div id="send_to">
<input type="radio" id="send_poll" name="people" value="all" checked="checked">all the attendees</br>
<input type="radio" id="send_poll" name="people" value="one" >only one attendee<br/>
<div id="send_to_one">
<label>Write the attendee's name: </label><input type="text" id="attendeename"><br/><br/>
</div>
<input type="radio" id="send_poll" name="people" value="group">a group of attendees</br>
</div>
I've checked that the javascript files are loaded. I also tried putting the javascript code inside the html.erb file where the form is, in a separated .js file and in application.htm.erb's <head></head> section, but no luck. Where do I need to put each part of code exactly in order to work?
Using Rails 3.0.4, Ruby 1.8.9. I'm also using JQuery
LIVE DEMO
HTML:
<div id="send_to">
<input type="radio" id="send_poll" name="people" value="all" checked="checked" />all the attendees<br/>
<input type="radio" id="send_poll" name="people" value="one" />only one attendee<br/>
<div id="send_to_one">
<label>Write the attendee's name: </label><input type="text" id="attendeename" /><br/><br/>
</div>
<input type="radio" id="send_poll" name="people" value="group" />a group of attendees<br/>
</div>
jQ:
$(document).ready(function(){
$("#send_to_one").hide();
$("input:radio[name='people']").change(function(){
if(this.value == 'one' && this.checked){
$("#send_to_one").show();
}else{
$("#send_to_one").hide();
}
});
});
$(document).ready(function() {
$("#send_to_one").hide();
$("input:radio[name='people']").change(function(){
if(this.checked){
if(this.value =='one'){
$("#send_to_one").show()
}else{
$("#send_to_one").hide();
}
}
});
});
Your code was right, but a few missing braces, brackets, and unescaped quotes. Are you using any form of smart javascript editor? Because you really should...
http://jsfiddle.net/7yt2A/
Related
If Field 1 is checked "Yes" then Field 2 should be checked "Yes"
This is what I've been trying so far:
Field 1:
<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field1||Question15||ENDFIELDTAG|| </label></div>
<div class="col9"><input type="radio" name="Field1" id="Question15yes" value="Yes" onclick="Check()">Yes <input type="radio" name="Field1" value="No" onclick="Check()">No</div>
Field 2:
<div class="entire">
<div class="col3"><label class="label-right">||FIELDTAG Field2||Question16||ENDFIELDTAG|| </label></div>
<div class="col9"><input type="radio" name="Field2" id="Question16yes" value="Yes" onclick="Check()">Yes <input type="radio" name="Field2" value="No" onclick="Check()">No</div>
I was trying something as simple as this js below, but I'm definitely missing something. Any help would be greatly appreciated!
<script language="JavaScript">
function Check() {
$("#Question15yes").click(function(){
if ($(this).is(':checked'))
{
$("#Question16yes").val("Yes");
}
}
});
}
</script>
Make sure you are including JQuery in your page.
To bind your event, you need to wait that the DOM is fully loaded, else you would try to use an element that doesn't exist yet.
<script language="JavaScript">
$(function() {
$(".question-checkbox").click(function(){
if ($(this).is(':checked'))
{
console.log($(this));
}
});
});
</script>
Also, you might want to change the JQuery selector from ID to class, so that you can use the same code for all similar checkboxes.
Put a .question-checkbox class on the inputs, and remove all onclicks.
You don't have to call check on every click. Once document loads, call it once.
window.addEventListener("load", function(){
$("input[type='radio']").on("click", function(){
if($("#Question15yes").is(':checked'))
$("#Question16yes").prop("checked", true);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entire">
<div class="col3">
<label class="label-right">||FIELDTAG Field1||Question15||ENDFIELDTAG|| </label>
</div>
<div class="col9">
<input type="radio" name="Field1" id="Question15yes" value="Yes">
Yes
<input type="radio" name="Field1" value="No" >No
</div>
<div class="entire">
<div class="col3">
<label class="label-right">||FIELDTAG Field2||Question16||ENDFIELDTAG|| </label>
</div>
<div class="col9">
<input type="radio" name="Field2" id="Question16yes" value="Yes">
Yes
<input type="radio" name="Field2" value="No">
No
</div>
Use this for a single checkbox with the class name "example":
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you
I have a problem and i do not find where it is, I explain to you I have a page.php which integrates a form.php and in this page.php I have a page1.php which is integrating also and which also has the form.php, and in this form I have Checkbox only my functions jquery works fine with pahe.php but not with page1.php and I do not understand why
page.php
<div class="left" style="float: left;">
<?php include('C_User_file/Planning/Form/Start/FStartT1.php'); ?>
</div>
page1.php
<div class="left" style="float: left;">
<?php include('C_User_file/Planning/Form/Start/FStartT1.php'); ?>
</div>
FStartT1.php
<label>
<input type="checkbox" id="cbox1" value="1" checked="checked" name="ALL1">
ALL
</label>
<label>
<input type="checkbox" id="cbox2" value="1" name="FMS1">
FMS
</label>
<label>
<input type="checkbox" id="cbox3" value="1" name="CPT1">
CPT
</label>
jquery.js
$("#cbox1" ).click(function(){
$('input[name=ALL1]').attr('checked', true);
$('input[name=FMS1]').attr('checked', false);
$('input[name=CPT1]').attr('checked', false);
});
$("#cbox2" ).click(function(){
$('input[name=ALL1]').attr('checked', false);
$('input[name=FMS1]').attr('checked', true);
$('input[name=CPT1]').attr('checked', false);
});
$("#cbox3" ).click(function(){
$('input[name=ALL1]').attr('checked', false);
$('input[name=FMS1]').attr('checked', false);
$('input[name=CPT1]').attr('checked', true);
});
On page.php works fine but on page1.php this does not work at all, thanks for your help
Be careful, my page1.php is included in page.php
By looking at your code, I got to know one thig.
The FStartT1.php i.e your FORM which is being imported 2 times.
So technically you have 2 form fields when the page is loaded. If you have doubt, just hit ctr+u on chrome and check the page source. You find 2 forms.
The means the IDs are duplicating. SO jQuery is unable to process it. IDs must be unique.
So,the following sections won't work.
$("#cbox1" ).click(function(){
});
$("#cbox2" ).click(function(){
});
$("#cbox3" ).click(function(){
});
Solution:
Make it a class instead of ID. And call like this
<label>
<input type="checkbox" class="cbox1" value="1" checked="checked" name="ALL1">
ALL
</label>
<label>
<input type="checkbox" class="cbox2" value="1" name="FMS1">
FMS
</label>
<label>
<input type="checkbox" class="cbox3" value="1" name="CPT1">
CPT
</label>
And in your jQuery,
$(".cbox1" ).click(function(){
});
$(".cbox2" ).click(function(){
});
$(.cbox3" ).click(function(){
});
Alternative Solution: Radio fields
Is there any reason for you not to use radio fields?
If someone (for whatever reason) has JavaScript disabled in their browsers settings, that person would be able to check and combination of your checkboxes.
<label>
<input type="radio" class="cbox1" value="1" checked="checked" name="events">
ALL
</label>
<label>
<input type="radio" class="cbox2" value="1" name="events">
FMS
</label>
<label>
<input type="radio" class="cbox3" value="1" name="events">
CPT
</label>
Use the below jQuery:
$("input[type=checkbox]" ).click(function(){
$("input[type=checkbox]" ).each(function(){
$(this).attr('checked', false);
});
$(this).attr('checked', true);
});
Try the above jquery code.
Explanation:
You are using the jquery selector as id and you are including the page1.php in page.php and both page has included FStartT1.php page. So you have same checkboxes with same id twice.
That's why your jquery code is working for first one not for second one.
Remember the id must be identical for HTML page and for jQuery also.
And I have right a generic jQuery code.
This question already has answers here:
How to check a radio button with jQuery?
(33 answers)
Closed 6 years ago.
I have this portion of code:
var checkout_options = $("#checkout").find("input[type='radio']");
$('#button-account').on('click', function () {
alert(checkout_options.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
<input type="button" value="Continue" id="button-account">
</div>
What I want it is to get the value of the selected radio button but with my code I only get the first radio button value, the second radio does not work.
Kindly help me fix the error.
You need to use this to refer the element inside the callback. So get value by using this.value or $(this).val() method. Although avoid :checked pseudo-class selector otherwise it only selects the first element.
var selected = $("#checkout").find("input[type='radio']");
selected.change(function(){
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b></label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
You can make it simpler using :radio pseudo-class selector
$("#checkout :radio").change(function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="checkout">
<p>Checkout Options:</p>
<label for="register">
<input type="radio" name="account" value="register" id="register" checked>
<b>Register Account</b>
</label>
<br>
<label for="guest">
<input type="radio" name="account" value="guest" id="guest">
<b>Guest Checkout</b>
</label>
</div>
Your handler is only being attached to the radio button that is checked, so no handler exists for the second radio button. Attach a handler to both radio buttons:
var $radioBtn = $( "#checkout" ).find( "input[type='radio']" );
$radioBtn.on( 'change', function() {
if ( this.checked ) {
alert( this.value );
}
});
It didn't work, because you register the event handler for the initially checked value only. This is how to make it dynamically reflect the value change:
var selected = $("#checkout").find("input[name='account']");
selected.change(function(){
alert($(this).val());
});
This also makes sure that only the current radio button group is included, so you can have additional ones.
Jsfiddle:
https://jsfiddle.net/sjmhdasw/
Just use
$("input[type='radio']").on("change", function() {
console.log(this.id + " checked !");
});
It binds an event listener on all the inputs of type radio !
No need to store the selectors inside a variable (unless you're doing something with it, somewhere else in your code)
Given the following code (yes, i know it is perhaps irrelevant in yii, but I added the tag so I update the question with the actual generated html):
<script>
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
}).change();
});
</script>
<div id="widgetId-dialog">
<form id="widgetId-form" action="/support/test" method="post">
<div>
<input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" />
<label for="single">Valor simple</label>
<input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" />
</div>
<div>
<input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" />
<label for="range">Rango (inicio:fin:intervalo)</label>
<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" />
</div>
</form>
</div>
It doesn't trigger change() when a radio becomes unchecked. This implies: controls are disabled only on initialization (.ready()). change() is not triggered individually by controls losing the checkmark.
Question: how can I detect when a radio button loses the checkmark?
This is a conceptional problem. The radio buttons are seen somehow like one element. For closer information look at Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?.
So the change-event will always only fire on the newly selected element and not on the deselected radios. You could fix your code like this:
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
//could be also hardcoded :
$('input[name="' + $(this).attr("name") + '"]').each(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
});
});
$('#widgetId-form input[name="valueType"]:first').change();
});
You can check it at http://jsfiddle.net/jg6CC/. Greets another Luis M. ;)