.toggle() issue with jquery - javascript

I have a form wherein there is a question where you can select multiple answer including Others by ticking the checkboxes. Then you tick others, it's suppose to show a textbox and when unticked, it should hide the textbox again.
What happens is when I untick it, yes it hides but the validation error still pops up. I'm not sure what's causing it. In other words, despite the fact that it is hidden, it is still validating.
Here's my javascript:
$("input[name = 'production-up']").change(function () {
//check if the selected option is others
if (this.value === "other") {
//toggle textbox visibility
$("#productionUpOther").toggle();
}
});
and my HTML:
<span id='productionUp' class='level'>
<p>Production - Reasons why it is up. Click as many as apply.</p>
<input type='checkbox' name='production-up' value='Increase in demand' required>Increase in demand <br/>
<input type='checkbox' name='production-up' value='Expected increase in demand'>Expected increase in demand <br/>
<input type='checkbox' name='production-up' value='Fullfillment of past orders'>Fulfillment of past orders <br/>
<input type='checkbox' name='production-up' value='Increased marketing activity'>Increased marketing activity <br/>
<input id="other" type="checkbox" name="production-up" value='other' />Other
<input id='productionUpOther' name='other-production-up' type='text' required/>
</span>
Be informed that this is just a part of my code. Any ideas on how to do something about this?!
Here you can that I ticked other
But when I untick it and press Next it still needs to be validated.

You can try this:
$("input[name = 'production-up']").change(function () {
//check if the selected option is others
if (this.value === "other") {
//toggle textbox visibility
$("#productionUpOther").toggle();
if (this.checked) {
$("#productionUpOther").attr('required','1');
} else {
$("#productionUpOther").removeAttr('required');
}
}
});

What you wanna do is disabling the text field 'other'. So in this case, I would use the 'disabled' property and then hide the field using CSS.
An example could be :
JS
$("#productionUpOther").prop('disabled', true);
$("input[name = 'production-up']").change(function () {
var hasTheFieldToBeEnabled = this.value === "other" && this.checked;
$("#productionUpOther").prop('disabled', !hasTheFieldToBeEnabled);
});
CSS
:disabled
{
display: none;
}
Here, all the disabled fields are hidden... But CSS is your friend if that's not what you want ^^
/!\ Careful: IE <8 doesn't support ':disabled', so if you want to support IE 8, you should add a class to the input when disabling it

try this
$("#productionUpOther").hide();
$("input[name = 'production-up']").change(function () {
//check if the selected option is others
if (this.value === "other" && this.checked) {
//toggle textbox visibility
$("#productionUpOther").show();
}
else{
$("#productionUpOther").hide();
}
});
see DEMO

You can directly use ID Selector ("#ID")
$("input#other").change(function () {
$("#productionUpOther").toggle(this.checked);
$("#productionUpOther").prop('required', this.checked);
});

Related

Express handlebars, can't bind checked attribute to checkbox

I am opening some divs when a user clicks on a certain checkbox like so:
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
var inputValue = $(this).attr("value");
if ($(this).prop("checked") == true) {
$("." + inputValue).show();
}
else if ($(this).prop("checked") == false) {
$("." + inputValue).hide();
}
});
});
Then, I store the classes of the checked boxes and if the user gave me bad input I redirect them to the submission page, I store the checked boxes like so:
allEvents={'coinChecked':true,'crinChecked':true,'ppChecked':false,'quizChecked':false}
Now I pass this allEvents object back to the submission page with res.render(check:allEvents)
Then, I use the following code (on SO) to bind the checked attribute to a checkbox, and hence open the initially hidden div with :
<input type="checkbox" name="events" value="coin" {{bindAttr checked="check.coinChecked"}}> Code-in
But neither does this make the checkbox "checked", nor does it display the hidden div.
How can I do this, or is there a workaround for this process?
thanks
<input type="checkbox" name="events" value="coin" checked={{if(check.coinchecked){{checked}}}}> Code-in
might do the trick

Prevent user from clicking radio again and without disabling it

<input type="radio" id="Svar0" name="Svar" value="Yes">
<input type="radio" id="Svar1" name="Svar" value="No">
<input type="radio" id="Svar2" name="Svar" value="MayBe">
User can choose only once.
As per requirement, if the user has selected a radio, he can not select another one. Means that if the user has answered YES (clicked on YES), then he can not change the answer to NO or MayBe.
Workarounds:
If I disable the radio after single click then it is not submitted to the server.
There is no option for readonly.
I tried onchange handler returning false, but it makes the user answer disappearing.
<script>
$('input[type = "radio"]').change(function () {
this.checked = false;
});
</script>
I am thinking of weird options like transparent div before radio buttons.
I do not want to prefer hidden fields as I have above 60 questions and I find it difficult to manage them.
Please help me any code in Jquery or Javascript.
If the user selects one answer in radio, then the page should not allow him to select another answer and so the first selected answer should be the one that gets submitted.
Another simple option (disable all, except selection, on selection of any). This allows the selected value to be posted back:
$(':radio').change(function(){
$(':radio').not(this).prop("disabled", true);
});
JSFiddle: http://jsfiddle.net/9n8v4heo/
Update (delay before disable):
It does not appear to be a good user experience to allow radio selection then freeze it immediately, as mistakes do happen.
The following example will allow a 2 second delay after any selection, before making them disabled, so you can keep clicking but after two seconds you cannot select again:
var tme;
$(':radio').change(function(){
var t = this;
clearTimeout(tme);
tme = setTimeout(function(){
$(':radio').not(t).prop("disabled", true);
}, 2000);
});
JSFiddle: http://jsfiddle.net/9n8v4heo/1/
try
$("[type=radio][name=Svar]").change(function () {
if (!$("[type=radio][name=Svar]").filter("[clicked]").length) {
$(this).attr("clicked", "true")
} else {
$(this).prop("checked", !this.checked);
$("[type=radio][name=Svar]").filter("[clicked]").prop("checked", true)
}
});
DEMO
use preventDefault() with click event as #JotaBe said
$("[type=radio][name=Svar]").click(function (e) {
if (!$("[type=radio][name=Svar]").filter("[clicked]").length) {
$(this).attr("clicked", "true")
} else {
e.preventDefault();
}
});
DEMO
You can disable the other buttons when one gets selected, this way the selected one will get sent when the form is submitted.
jQuery("input[name=Svar]").change(function() {
jQuery("input[name=Svar]").prop("disabled", "disabled");
jQuery(this).prop("disabled",false);
});
You can attach an event handler that disables the default action for the click to all the radios, and do whatever you need to do instead ofteh default action. Tod so so, attach a handler that simply includes a call to: event.preventDefault(), and your own code.
See jquery docs for event.preventDefault()
$(document).ready(function() {
var allowChoose = true;
$('input').click(function(e) {
if (allowChoose) {
allowChoose = false;
} else {
e.preventDefault();
}
});
});
As you can see, you can use a flag like 'allowChoose' to allow the default action on the first click, and then change the flag and avoid the default action (checking the radio) on the next calls.
See the fiddle here.
Quick solution: You can disable the others radio buttons and the selected value remains enabled.
var $Svars = $('input[name="Svar"]');
$Svars.change(function () {
$Svars.not(this).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="Svar0" name="Svar" value="Yes" /> Yes
<input type="radio" id="Svar1" name="Svar" value="No" /> No
<input type="radio" id="Svar2" name="Svar" value="MayBe" /> Maybe
Solution 2: Another solution will be to add a class or a data attribute to exclude the others, like below.
var $Svars = $('input[name="Svar"]');
$Svars.change(function () {
var $this = $(this);
if($this.val() == $this.data('selected') || $this.data('selected') == undefined) {
$Svars.data('selected', $this.val());
} else {
$Svars.val([$this.data('selected')]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="Svar0" name="Svar" value="Yes" /> Yes
<input type="radio" id="Svar1" name="Svar" value="No" /> No
<input type="radio" id="Svar2" name="Svar" value="MayBe" /> Maybe

$('input[type=checkbox]').change(function()

Currently Im have the following script which checks to see if a checkbox value has changed but its not working when I try to use it!
<script>
$('input[type=checkbox]').change(function () {
if ($(this).is(':checked')) {
if ($(this).prev().attr('checked') && $(this).val() != $(this).prev().val()) {
alert("previous checkbox has same value");
}
}
});​
</script>
<input name="" type="checkbox" value="here"/>(if this was checked)
<input name="" type="checkbox" value="here"/>(then this)
<input name="" type="checkbox" value="there"/>(would not allow prompt alert)
<input name="" type="checkbox" value="here"/>(would allow)​
you can see it working here yet it does not work when i try to use it
http://jsfiddle.net/rajaadil/LgxPn/7
The idea is to alert when a checked checkbox value is different from the previously checked checkbox value!
Currently my checkbox look like
<input type="checkbox" name="checkbox[]" onClick="getVal();setChecks(this)" value="`key`=<?php echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>"/>
I thought the function ('input[type=checkbox]').change(function() would get these but im wrong somewhere?
To select the previous checked sibling checkbox, use this:
$(this).prevAll(":checked:first")
I expected to use :last, but :first is what works. This is counter-intuitive to me and inconsistent with how :first and :last usually work, but I tested it in several browsers and the result is consistent.
$(':checkbox').change(function() {
if (this.checked) {
var lastChecked = $(this).prevAll(":checked:first");
if (this.value == lastChecked.val()) {
alert("previous checked box has same value");
}
}
});
Demo: http://jsfiddle.net/LgxPn/15/
Edit: If by "previously checked checkbox" you mean the last box the user clicked, then you'll need to keep track of that yourself. There's no built-in jQuery method that will tell you anything about click history.
What happens when the user first checks several boxes, and then checks and immediately unchecks a box? Should the next most recently checked box be used? If so, then you need to keep track of all checked boxes, and what order they were clicked. Here's how you can keep track of the checked boxes:
var lastChecked = [];
$(':checkbox').change(function() {
if (this.checked) {
if (lastChecked.length && this.value == lastChecked[0].value) {
alert("the last box you checked has the same value");
}
lastChecked.unshift(this);
}
else {
lastChecked.splice(lastChecked.indexOf(this), 1);
}
});​
Demo: http://jsfiddle.net/LgxPn/21/
Just a guess (with some better syntax), try this:
<script type="text/javascript">
$(function() {
$('input:checkbox').change(function() {
if($(this).is(':checked'))
{
if ($(this).prev().prop('checked') && $(this).val() != $(this).prev().val()) {
alert("previous checkbox has same value");
}
}
});​
});
</script>
Your alert message and your if statement don't match. You check to see if the values !=, but the alert says they are equal. I'm assuming the alert is the case you want to check for. Try:
$(':checkbox').change(function() {
var $this = $(this);
var $prev = $this.prev();
if($this.is(':checked')) {
if($prev.is(':checked') && $this.val() === $prev.val()) {
alert('Previous checkbox has same value');
}
}
});​
And as the others mentioned, make sure this is all within a $(document).ready() block
This seems to work for me in Chrome:
$(function() {
$('input[type=checkbox]').click(function() {
if ($(this).is(':checked')) {
if ($(this).prev().prop('checked')) {
if ($(this).val() != $(this).prev('input[type=checkbox]').val()) {
alert("previous checkbox has same value");
}
}
}
});
});​
Here's a JSFiddle: http://jsfiddle.net/gy8EQ/

checkbox property using jquery

i m a beginner.
i want that when a checkbox is checked then it should allow user to write something in a txtbox. initially the txtbox is disabled. what i should write inside the function using jquery
<input type="checkbox" id="cb" />
<label for="cb">label for checkbox</label>
<input type="text" id="txt" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function() {
var checkbox = $('#cb');
var textfield = $('#txt');
checkbox.click(function() {
if (checkbox.is(':checked')) {
textfield.removeAttr('disabled');
}
else {
textfield.attr('disabled', 'disabled');
}
});
});
</script>
working example with visibilty
working example with disabled-state
additionally:
as you are working with asp.net, your assignments should look like, eg:
var checkbox = $('#<%= this.cb.ClientID %>');
you should be aware of the way how the server-controls get rendered either (to choose an appropriate selector).
furthermore: you should also be aware of the fact, that disabled-inputs won't get posted, whereas readonly-inputs are no problem to handle...
$('#mycheckbox').click(function()
{
$("#mytextbox").attr('disabled','');
}
);
$(document).ready(function()
{
//To Disable the Check box on page Load
$('#TextBox').attr('disabled', 'disabled');
//On Click of the Check Box
$('#CheckBoz').click(function()
{
if($('#CheckBoz').is(':checked'))
{
$('#TextBox').removeAttr('disabled');
}
else
{
$('#TextBox').attr('disabled', 'disabled');
}
});
});
I Hope this code works perfectly for you and u jst need to paste it in your page and check the Component name according to it.

jQuery: Problems with detecting if a checkbox is checked

I'm creating a small jQuery plugin for my CMS that styles certain form input types (just radio, checkbox at the moment). It works by hiding the original form element and placing a normal HTML element (for styling with CSS) in the input's place. It then detects actions on the element and updates the original input accordingly. Additionally, it will also work when the associated label is clicked. Here is my code:
jQuery.fn.ioForm = function() {
return this.each(function(){
//For each input element within the selector.
$('input', this).each(function() {
var type = $(this).attr('type');
//BOF: Radios and checkboxes.
if (type == 'radio' || type == 'checkbox') {
var id = $(this).attr('id');
checked = '';
if ($(this).attr('checked')) {
checked = 'checked';
}
//Add the pretty element and hide the original.
$(this).before('<span id="pretty_'+ id +'" class="'+ type +' '+ checked +'"></span>');
$(this).css({ display: 'none' });
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function() {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').removeAttr('checked');
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id).removeAttr('checked');
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
}
}
});
} //EOF: Radios and checkboxes.
});
});
};
This works great for the radio, but the checkbox seems to get stuck when clicking the checkbox label for a second time - the first click of the label successfully changes it to the appropriate state, but clicking the label again doesn't change it (however the checkbox itself still works fine). It works perfectly in IE8.
I've checked the id is correct and it is. I've also tried a few other methods I stumbled across of checking if the checkbox is checked, but they either gave the same result or failed altogether. :(
Any help would be much appreciated.
Thanks :)
Update
Here is the HTML, which is generated by a PHP class. This is after the jQuery has run and added in the span elements:
<div>
<p class="label">Test:</p>
<span id="pretty_test_published_field" class="checkbox"></span>
<input class="checkbox" id="test_published_field" name="test" type="checkbox" value="published">
<label for="test_published_field" class="radio">Published</label>
<span id="pretty_test_draft_field" class="checkbox"></span>
<input checked="checked" class="checkbox" id="test_draft_field" name="test" type="checkbox" value="draft">
<label for="test_draft_field" class="radio">Draft</label>
</div>
Just use the infallible and extremely simple DOM checked property. jQuery is inappropriate for this and apparently makes one of the simplest JavaScript tasks there is error-prone and confusing. This also goes for the id and type properties.
$('input', this).each(function() {
var type = this.type;
if (type == 'radio' || type == 'checkbox') {
var id = this.id;
var checked = this.checked ? 'checked' : '';
// Etc.
}
});
UPDATE
The default action of clicking a <label> element associated with a checkbox is to toggle the checkbox's checkedness. I haven't tried this myself with labels for hidden form elements, but perhaps the toggling is still happening because you're not preventing the browser's default click action. Try the following:
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function(evt) {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').each(function() {
this.checked = false;
});
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
evt.preventDefault();
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id)[0].checked = false;
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
}
evt.preventDefault();
}
});
i've found on the odd accassion that i need to use the alternative of:
$("#checkboxID").is(':checked');
this may or not be an alternative in your scenario, but worth noting. Also, you may have to add the 'live' event, rather than 'click' if changes to the dom are occurring. i.e.
.click(function()
to
.live('click', function()
jim
The checked attribute of a checkbox is mapped to the defaultChecked property and not to the checked property. Use the prop() method instead.
If elem is the checkbox, use:
elem.checked
or
$(elem).prop("checked")
This gives us the proper state information of the checkbox and changes as the state changes.
This seems to be the reason of confusion in many cases. So its good to keep in mind the underlying reason behind this.
Could you show us the HTML? I am looking to see if you set a value property for the checkbox in the HTML. There is a possibility that broke it.
<input type="checkbox" value="This May Break Checkbox" />
<input type="checkbox" name="This Checkbox Works" />

Categories

Resources