update text box based on checkbox selection jquery - javascript

I want to achieve following thing with Jquery
There are multiple trips and each trip has checkbox and textbox.
Whenever checkbox is checked then the value in textbox corresponding to that checkbox must be updated to "1" .
Whenever customer types in textbox then checkbox shall be checked
<input type="checkbox" id="ckval1" class="checkvaloare" />Trip 1 sadssad
<input type="text" id="text1" class="ckval" size="2" />
<br/>
<input type="checkbox" id="ckval2" class="checkvaloare" />Trip 2 sadsassad
<input type="text" id="text2" class="ckval" size="2" />
JQUERY as
$(function () {
$("input[type=checkbox]").on('click', function () {
$(this).next().val($(this).is(':checked') ? '1' : '0');
});
$("input[type=text]").on('keyup', function () {
if ($(this).val()) {
$(this).prev().prop('checked', true);
} else {
$(this).prev().prop('checked', false);
}
});
});
But this is not working and when i use JSF Tag <h:selectBooleanBox> then also it is not working.

You need to use nextAll and prevAll (along with the firstpseudo selector) as you have anchors in between your checkbox and textbox.
I would also change the click event to change
$(function () {
$("input[type=checkbox]").on('change', function () {
$(this).nextAll('.ckval:first').val($(this).is(':checked') ? '1' : '0');
});
$("input[type=text]").on('keyup', function () {
if ($(this).val()) {
$(this).prevAll('.checkvaloare:first').prop('checked', true);
} else {
$(this).prevAll('.checkvaloare:first').prop('checked', false);
}
});
});
Example

next() only get the next sibling element. In your case, the next sibling element after the checkbox are the tags. There are two sets of tags before your desired input, which is why it works for you after 3 'next()'s. Of course that is not very pretty to use 3 nexts and would break easily if you ever added another element in there.
use
nextAll('.ckval:first')
and it will find the next ckval input rather than the next element.

Related

.toggle() issue with jquery

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);
});

clear radio buttons when click on text input

I have a group of 4 radio buttons followed by a text input, when users click on the text input field I am trying to clear all radio inputs. here is my code so far.
<input type="radio" name="radio"><label for="radio1">1</label>
<input type="radio" name="radio"><label for="radio2">2</label>
<input type="radio" name="radio"><label for="radio3">3</label>
<input type="radio" name="radio"><label for="radio4">4</label>
<input type="text" id="textInput">
<script>
$('#textinput').click(function () {
radio.checked = false;
});
</script>
You can use .prop() to set checked property of input rabio buttons. Also you have misspelled textInput while event binding
<script>
$('#textInput').click(function () {
$('input[name="radio"]').prop("checked", false);
});
</script>
DEMO
<script>
$('#textInput').click(function () {
$('input[type=radio]').removeAttr("checked");
});
</script>
Or you can try attr() method
$('#textInput').click(function () {
$('input[name="radio"]').attr('checked',false);
});
DEMO
I think the best way to modify your script block (without changing your html) is first by ensuring that the code runs on document ready, and also you should probably ensure that the event is focus, not click, in case someone is using a keyboard or alternate navigation:
$(function() {
$('#textInput').focus(function () {
$('input[name=radio]').prop("checked", false);
});
});
Though it's probably more likely that you want to only clear other selections if they actually enter some data in that field, you might want to instead do:
$(function() {
$('#textInput').on('input', function () {
if($(this).val().length > 0) {
$('input[name=radio]').prop("checked", false);
}
});
});

How to make One Jquery script work for multiple inputs with slightly different name

I have a jquery keyup script that changes a data-attribute for a checkbox input when a text input value is changed. Currently it works for only one instance of a checkbox input and text input. However, I need to modify the script to work for 10 instances.
In this fiddle you can see that I have it working for the first instance number 1, but not for 2-10.
So for example, the script is triggered when a user changes the value of the input with the id="account_balance1" as seen below.
<input type="checkbox" checked="checked" data-cost="100" debt="" value="" name="f_2[]"/>
This is the input where the value is entered for the keyup event
<input type="text" maxlength="7" class="balance" id="account_balance1" name="cardbalance" value=""/>
But I need it to work for 10 instances of these two inputs; for each instance there is an li id=card_" and input id="account_balance_" that increase 1 increment, like this... li id="card_1" to li id="card_2" to li id="card_3" and so on. This is same for the input id="account_balance_1, it goes to _2 to _3 and so on.
This is the keyup script
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("input[data-cost][debt]").data('cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").data('debt',str.replace(/^\$/, ''));
$('#jquery-order-form').data('jprice').onChange();
}, 0)
})
});
Just change your jquery selector:
Instead of this:
$('#account_balance_1').on('keyup blur paste', function() {
do this:
$('.balance').on('keyup blur paste', function() {
This works because all your involved inputs have the class balance.
Fiddle here: http://jsfiddle.net/edgarinvillegas/8jdfJ/10/
Cheers
See this
http://api.jquery.com/attribute-starts-with-selector/
You just need to use this selector for selecting appropriate elements
$('[id^=account_balance_').on('keyup blur paste', function() {...

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 select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources