jQuery Checkbox event handling with .live() - html

Newbie to jQuery here. I have a check box that is dynamically added through the following code in jQuery:
.html("<input type='checkbox' class='checkbox' value='7.5'>");
I want to be able to eventually call a function if a checkbox is clicked. I have tried using these two variants of code:
for the class checkbox:
$(".checkbox").live('click', function() {
alert('test');
});
or to call all checkboxes:
$(":checkbox").live('click', function() {
alert('test');
});
This isn't working at all. Any ideas?
Much appreciated!

.live() is deprecated. Use the event delegation syntax:
$(document).on('change', 'input[type="checkbox"]', function(e) {
alert(e);
});
Replace document with the selector of the closest parent element that's present when you bind the event handler. I'd also suggest not to use :checkbox, as it's a non-native selector and will be slower than input[type="checkbox"]

Related

How to detect click event on any checkbox on a page using jQuery?

How can I detect that a click event is fired on any checkbox on a page using jQuery? Please also note that on page load, may be checkbox(s) is/are not created but could be created on request. So HTML DOM will be updated in that fashion.
$(":checkbox").on("click", function(){
// your work
} );
also see bind
delegate
live
reference On
TRy this
$( document ).on( "click", "input[type='checkbox']", function() {
alert( "check box clicked" );
});
$(":checkbox").on("click", function(){
// ALL YOUR STUFF
} )
Simply create a function checkboxClick() as -
function checkboxClick() {
// ---
// your code goes here
// ...
}
Now for every checkbox (even when you add them dynamically) add attribute onclick like
<input type="checkbox" onclick="javascript:checkboxClick();" class="checkbox" />
Note : Since javascript works on existing dom elements, even if you do something like jQuery(".checkbox").click(function() {...});, it wont work on dynamicically added elements
$(document).on('click', ':checkbox', function() {
//your code
});

Selecting Dynamic ID JQuery

I need to select dynamic id using JQuery, and once I select it then I need to do some action on it. This is the HTML that I have:
<input id="content_photos_attributes_1355755712119_image" name="content[photos_attributes][1355755712119][image]" size="30" type="file">
Please note the id value, text is always the same however the number changes (I do not have control over that change).
What I need to do is to create on click for that element. This is what I got so far, and it is not working.
<script type="text/javascript">
jQuery.noConflict();
jQuery("input[id *= 'content_photos_attributes_']").click(function() {
alert("Image deletion is clicked");
});
</script>
It really makes no difference whether I select that element by ID or by its name.
As i see this it should be in the $(document).ready(); handler and its a dynamic id so for this you have to use .on() handler to select the selector:
$(document).ready(function(){
jQuery(document).on('click', 'input[id^="content_photos_attributes_"]', function() {
alert("Image deletion is clicked");
});
});
try this and see if helps.
Try the starts with ^= selector:
$("input[id^='content_photos_attributes_']").click(function() {
alert("Image deletion is clicked");
});
Also you don't need the quotes inside the attribute comparison unless you're having the dot '.' character. This would also work:
$("input[id^=content_photos_attributes_]").click(function() {
alert("Image deletion is clicked");
});

How do I trigger a function to execute after external HTML is loaded?

JS:
$(document).ready(function(){
$("#loader").load("external.html");
$("#buttonClickText").live('click', function() {
$("#buttonClickText").text("Text changed after button click.");
});
// MYSTERY FUNCTION
$("#pageLoadText").text("Text changed after external HTML was loaded.");
//
});
External HTML:
<div id="buttonClickText">
This text changes when clicked.
</div>
<div id="pageLoadText">
This text should have changed when external HTML was loaded, but didn't.
</div>
Main HTML (just showing the relevant tag):
<div id="loader"></div>
Also, I know .live() is deprecated for jQuery 1.7+, I'm guessing the solution will be similar using .on()
Thanks!
from http://api.jquery.com/load/:
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data.
Just pass a function as the second argument.
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
below is the solution for the issue:
$(document).ready(function(){
$("#loader").load("external.html", function()
{
$("#pageLoadText").text("Text changed after external HTML was loaded.");
}
);
$("#buttonClickText").live('click', function() {
$("#buttonClickText").text("Text changed after button click.");
});
});

Is it possible to prevent file dialog from appearing? Why?

Suppose I have input[type=file] element and I want to intercept onclick event and prevent file dialog from appearing if conditions are not met. Is it possible? And why, if - not?
Soufiane's code requires that you have a Javascript library called jQuery on your page. If you don't have it, you can get it at http://www.jquery.com or use something in plain Javascript:
HTML
<input type="file" id="openf" />
JS:
document.getElementById('openf').onclick = function (e) { e.preventDefault(); };
HTML:
<input type="file" class="openf" />
JS:
$('.openf').click(function(e){
e.preventDefault();
});

html5 form checkValidity() method not found

I am trying to use the form method checkValidity().
http://html5test.com/ tells me that my browser (Chrome) support the form-level checkValidity method.
However, using jsfiddle http://jsfiddle.net/LcgnQ/2/ I have tried the following html and javascript snippets:
<form id="profileform" name="profileform">
<input type="text" id="firstname" required>
<input type="button" id="testbutton" value="Test">
</form>
$('#testbutton').bind('click',function(){
try{
alert($('#profileform').checkValidity());
}
catch(err){alert('err='+err)};
});
I'm getting an error: object has no method checkValidity()
What am I doing wrong?
Try:
$('#profileform')[0].checkValidity()
When you select $('#profileform') you get a jQuery object array. To access actual DOM properties you must select the first item in the array, which is the raw DOM element.
#robertc 's Answer is perfect. Anyway I'd just add another way to do it using jQuery's .get([index]) function. It also retrieves the DOM element for the given index, or all of the matched DOM elements if there's no index declared.
In the end it is exactly the same, only written in a bit more verbose way:
$('#profileform').get(0).checkValidity()
Leaving you the docs right here: https://api.jquery.com/get/
Just another way:
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByName('profileform');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
}, false);
});