JQUERY ON('change') get checkbox value and state - javascript

How can I "get" the checkbox that changed inside div "containerDIV"?
View:
#model MyModel
<div id="containerDIV">
<ul id="CheckBoxList">
#foreach (XObject t in MyModel.XCollection)
{
<li>
<input type="checkbox" value="#t.id"/>
</li>
}
</ul>
On the JavaScript (Jquery) side, I have this:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
It's clear that $this is not the checkbox, it's the div containerDIV or checkBoxList
How can I get to the checkbox's state and value?

If your input is not being created dynamically after the DOM loads you can just call:
$('#CheckBoxList input[type=checkbox]').change(function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
or to use .on() you just need to target the input that's getting clicked:
$('#CheckBoxList').on('change', 'input[type=checkbox]', function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
FIDDLE

The way i got it to work correctly was using .is(':checked').
$('selector').change(function (e) {
// checked will equal true if checked or false otherwise
const checked = $(this).is(':checked'));
});

If you can, add the events as an attribute, like onchange='function(this);'. This returns the element to the function, so you can get data such as it's ID, or just modify it like that.
Good Luck!

Following billyonecan comment, this is another way to do it:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id =$(event.target).val();
if (id != null) {
//do other things
}
});

Related

jQuery get / set value of textbox value in a repeater

I have a repeater with textboxes ID="txtBomName" in an ascx page with a value retrieved from datatable on pageload.
the end user can change the value, must be not be null/empty.
I have jquery to check if null/empty on change or blur, produce alert if null then I would like the null value set back to original else set value as user entered.
This does work if, I use the generated control ID i.e:
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName)"
this obviously only works for the the first textbox on the page, as the "ct100" part of the ID changes for each box.
code:
$(document).ready(function () {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").change(function () {
var oldVal = this.getAttribute('value');
if (this.value == null || this.value == "") {
alert("Please ensure the name is not empty");
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(oldVal);
}
else {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(this.value);
}
});
});
so, I changed the code to look for id$=txtBomName and set an alert to (this.id) the id for each box shows correctly, how can I set the value of the textboxes using (this.id).val(oldVal); ?
You need to use:
$(this).val(oldVal);
'this' is a reference to the current object i.e. textArea the abouve code will set the value of the textArea
Try this code
$(document).ready(function () {
// The simplest way is to save the original value using data() when the
// element gets focus.
$("input[id$='txtBomName']").on('focusin', function(){
$(this).data('val', $(this).val());
});
$("input[id$='txtBomName']").change(function () {
var txtBox=$(this);
var prev = txtBox.data('val');
var current = txtBox.val();
if (current) {
txtBox.val(current);
}
else {
alert("Please ensure the name is not empty");
txtBox.val(prev);
}
});
});

Testing input value in click handler

i have one textfield whose id is date. i want to give an dialog boxmsg when textfield is empty. i am tried the following code a lot times but it never going to execute button click function. Why this happen please tell me
var val = $('#date').val();
$(document).ready(function() {
$("#btnSubmit").click(function() {
if (val != null) {
$("#dialog").dialog();
return false;
}
});
});
Move var val = $('#date').val(); inside click handler so that val will always contain the latest value in the #date input.
$(document).ready(function() {
$("#btnSubmit").click(function() {
var val = $('#date').val().trim(); // Remove leading and trailing spaces
// Moved inside click handler
if (!val) { // Check if falsy value
$("#dialog").dialog();
return false;
}
});
});
Looks like your val variable scope is different. So you can try something like:
$(document).ready(function () {
$("#btnSubmit").click(function(){
if ($('#date').val()){
$("#dialog").dialog();
return false;
}
});
});
Something like this? Gets the value when you click and alerts if it's empty?
You need to get the textbox's value when you click, otherwise it will be empty since it's going to be set ONCE, when the page loads.
$(document).ready(function () {
$("#btnSubmit").click(function(){
var textbox = $('#textbox').val();
if (textbox.length == 0){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="textbox" type="text" placeholder="Type here"><br>
<button id="btnSubmit">Click me</button>

boolean variable in jquery

I have some issues. I have checkbox in my jsp page. So if the checkbox is checked i have to set a boolean variable to true else false. I tried something like this
<script>
$(document).ready(function() {
$(".confirmCheckbox").change(function() {
boolean confirmAssignee = false;
$(this).attr("checked") {
confirmAssignee = true;
}
alert(confirmAssignee);
});
});
But it is giving this error
SyntaxError: missing ; before statement
$(this).attr("checked") {
I have mutliple checkboxes on the page. Sample code is like this :
for loop(----)
<input type="checkbox" id="confirmBox-${loopCounter.index}" class = "confirmCheckbox">
Any help will be appreciated. Ask anything if required.
You need to use var while defining variable and use this.checked or .prop() to get whether checkbox is checked or not.
Simple statement will do it.
var confirmAssignee = this.checked; //OR $(this).prop("checked");
Complete Script
$(document).ready(function() {
$(".confirmCheckbox").change(function() {
var confirmAssignee = false;
if (this.checked) {
confirmAssignee = true;
}
alert(confirmAssignee);
});
});
There is not boolean type use var
Change
boolean confirmAssignee = false;
To
var confirmAssignee = false;
You also miss the if in the state $(this).attr("checked") { it should be if($(this).attr("checked")) {
Note use prop for checkbox instead of attr as suggest be jQuery doc.
For example, selectedIndex, tagName, nodeName, nodeType,
ownerDocument, defaultChecked, and defaultSelected should be retrieved
and set with the .prop() method. Prior to jQuery 1.6, these properties
were retrievable with the .attr() method, but this was not within the
scope of attr. These do not have corresponding attributes and are only
properties.
You can simplify code like
Live Demo
$(".confirmCheckbox").change(function () {
alert(this.checked);
});
Javascript have auto data types you didn't need to declare data types it is automatically taken in javascript. To check the checkbox using this.checked
$(".confirmCheckbox").change(function () {
var confirmAssignee = false;
if (this.checked) {
confirmAssignee = true;
}
alert(confirmAssignee);
});
Two problem in your code
one there is no boolean datatype in javascript use var instead of boolean
secondly you need to check if checkbox is checked or not in if condition
use below code:
$(document).ready(function() {
$( ".confirmCheckbox" ).change(function() {
var confirmAssignee = false;
if($(this).attr("checked")) {
}
alert(confirmAssignee);
});
});
1)use var instead of of boolean
var confirmAssignee = false;
2)use checkbox checked property
if($(this).is(':checked'))

Using jquery to monitor form field changes

Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.
$(function(){
setInterval("CheckDirty()",10000);
$(':input').each(function() {
$(this).data('formValues', $(this).val());
});
});
function CheckDirty()
{
var isDirty = false;
$(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
}
Just add a class to the form and use it to filter
$('.form :input').each(function() {
$(this).data('formValues', $(this).val());
});
EDIT
Just a suggestion, you can attach the change event directly to the form
live demo here : http://jsfiddle.net/jomanlk/kNx8p/1/
<form>
<p><input type='text'></p>
<p><input type='text'></p>
<p><input type='checkbox'></p>
</form>
<p><input type='text'></p>
<div id='log'></div>
$('form :input').change(function(){
$('#log').prepend('<p>Form changed</p>')
});
You can easily improve this by adding a timer and making it save every xx seconds.
var $jq= jQuery.noConflict();
$jq(function() { $jq('#extensibleForm').data('serialize',$jq('#extensibleForm').serialize());
});
function formHasChanged(){
if($jq('#extensibleForm').serialize()!=$jq('#extensibleForm').data('serialize')){
alert("Data Changed....");
return (false);
}
return true;
}
what's your form's id?
you just need to make your selector more specific :)
instead of $(':input').each(function() {
use
$('#yourFormId').find(':input').each(function() {
You can use the .change() function and then use $(this) to denote you want to work with just the field that is actively being changed.
$('#myForm input[type="text"]').change(function() {
$(this)...
});
Edit: #myForm is your form ID so you can target a specific form. You can even specify just type="text" fields within that form, as in my example.
Here you can see it working: http://jsfiddle.net/paska/zNE2C/
$(function(){
setInterval(function() {
$("#myForm").checkDirty();
},10000);
$("#myForm :input").each(function() {
$(this).data('formValues', $(this).val());
});
$.fn.checkDirty = function() {
var isDirty = false;
$(this).find(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
};
});
I think you can use a class to select the type of input you want.
<input class="savethis" ... />
Then in jQuery use this.
$(':input .savethis').each(function() { ...
You can specify an id attribute (say theForm) to your form element and then select only those input fields inside it.
then try selecting with
$(':input', '#theForm')
I respect all the working answers but for me I think using the focus event might be much better than change event. This is how I accomplished my watchChange() function is JS:
var changeInterval = 0;
var changeLength = 0; //the length of the serverData
var serverData = {value:''}; //holds the data from the server
var fieldLength = 0; //the length of the value of the field we are tracking
var frequency = 10000;
function watchChange() {
$input.on('focus', function() {
var $thisInput = $(this);
//we need the interval value so that we destroy
//setInterval when the input loses focus.
changeInterval = setInterval(function() {
changeLength = serverData.value.length;
fieldLength = $thisInput.val().length;
//we only save changes if there is any modification
if (changeLength !== fieldLength) {
$.ajax({
url: 'path/to/data/handler',
dataType: 'json',
data: "data=" + $thisInput.val(),
method: 'post'
}).done(function(data) {
serverData = data;
}); //end done
} //end if
}, frequency); //end setInterval
//and here we destroy our watcher on the input
//when it loses focus
}).on('blur', function() {
clearInterval(changeInterval);
});
}
Even though this approach seems to be naive but it gave me what I wanted!

Locating Hidden Field Using JQuery

Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length) returns 0. In fact, alert(jQuery('div#toggleParent h2').length) returns 0 even though the click event on that exact element just fired!
What am I missing?
This:
document.ready(function () {...});
Should be:
jQuery(document).ready(function () {...});
Or even:
jQuery(function () {...});
Or...
jQuery(function ($) { /* Use $ in here instead of jQuery */ });
Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:
jQuery('#toggleValue').val(toggle);
Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use
var toggle = jQuery('div#toggleParent input#toggleValue').val();
I propose this code:
jQuery(function($) {
var toggleParent = $('#toggleParent')[0],
toggleValue = $('#toggleValue')[0];
$(toggleParent).find('h2').click(function() {
toggleValue.value = toggleValue.value === 'closed' ? 'open' : 'closed';
});
});
Try this code:
$(document).ready(function() {
var toggle;
$('div#toggleParent h2').click(function() {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
$('div#toggleParent input#toggleValue').val(toggle);
alert($("input#toggleValue").val()); // check what the new value is
});
});

Categories

Resources