I am new to coding and I need to use Javascript in my code. I have a checkbox within an HTML table (below).
<td><input type="checkbox" id="check1"/>
<label th:text="${item.contents}"> </label>
</td>
I am trying to use Javascript to alert me when I have checked the box with the code below.
<script>
$('#check1').click(function() {
if($(this).not(':checked'))
alert('unchecked');
else
alert('checked');
});
</script>
Why isn't it working? I don't get an error, but nothing happens either.
Thank you.
Ok, first, you have some syntax that is not HTML here:
<label **th:text="${item.contents}"**>
And, if that non-HTML code is incorrect, that could be enough for the page to stop processing. You say you don't get an error, but do you mean that you've checked your developer tools console window and don't see an error there?
As for the checkbox, neither the table cell, nor the label are related to your goal.
Next, JQuery is a great thing, but it sometimes makes things that are already easy, harder. Your code is actually EXCLUDING any checked elements from the wrapped set that will be examined because you are using not().
Here is a solution that doesn't rely on JQuery:
var chk = document.getElementById("check1");
chk.addEventListener("click", function(){
// The following is not part of your question, but is
// added just for completeness:
// Because the alert() is modal, it will block the UI
// from updating and it will most likely appear before
// the UI updates the checkbox to the latest appearance.
// To solve this, we add a short delay before making the
// alert using a timer and we need to store the checked
// status of the checkbox outside of the timer's callback
// function.
var on = this.checked;
setTimeout(function(){
var message = "checked";
if(!on){
message = "un" + message;
}
alert(message);
}, 50);
});
<input type="checkbox" id="check1">
I don't think it's normally very wise to listen to click events on things like checkboxes and radio buttons. From what I understand they may be triggered before the value of the input is updated, depending on where you catch the event in the dom.
I'm not sure what the html syntax is on your label, the th:text part, but it seems to be some sort of templating syntax and also may be unrelated. To help simplify the problem also I will give you an example without using jQuery, jQuery often adds unnecessary complexity to simple problems.
A properly working example of your code using vanilla javascript (without jquery) would be,
document.getElementById("check1").addEventListener('change', function(e) {
var checked = this.checked;
if(checked) { alert("Checked"); }
else { alert("Unchecked"); }
});
And with jquery, a working example is:
$("#check1").on("change", function(e) {
var checked = this.checked;
if(checked) { alert("Checked"); }
else { alert("Unchecked"); }
});
Related
I am trying to write a code within a form input such as when the user clicks on the form element (onfocus), the value of the element disappears, but if a user click on any other input element after that (without filling up the previous input element of the form) than the value of the previous element reappears.
The HTML code is shown below:
<label id="color_text">Forename:</label><br />
<input id="f1" class="form-control" type="text" name="forename" value="Forename" /><br /><br />
The JavaScript i am trying to run is shown below:
<script>
var new_id = document.getElementById("f1");
new_id.onfocus = function(){
if (new_id.value == "Forename"){
new_id.value = "";
}
};
new_id.onblur = function() {
if (new_id.value == ""){
new_id.value = "Forename";
}
};
For maximum compatibility you should use addEventListener or attachEvent (whatever is available). So for focus event something like this:
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
addEvent(new_id, 'focus', function() {
if (new_id.value == "Forename"){
new_id.value = "";
}
});
You should read this about events binding. And probably use placeholder in first place, if I am right about what you are trying to accomplish.
Your code works just fine. http://jsfiddle.net/bigneo/7j217d8y/
I think the problem is your methods are not seen by the document. You could wrap them inside document.ready
Something like this, but requires jQuery:
$(document).ready(function() {
// your methods here
});
Your code is fine, you just need to tell the browser when to run it. Wrap it in this:
document.addEventListener('DOMContentLoaded', function() {
// code goes here
});
This is a much better option for vanilla JS rather than importing the whole JQuery library just to use $(document).ready(function()
Your code works fine in Chrome 44. What's your browser?
And why don't you use placeholder attribute in the <input> label?
So, I have this weird IE10-Bug (IE11 works correctly):
I've got a checkbox like this:
<div class="select-row row-b">
<p>some text</p>
<label><input type="checkbox" name="checkboxGroupA" data-index="1" value="A1"/>A1</label>
</div>
Using Fancyform-jQuery-Plugin v 1.4.2, it seems there's a bug in Fancyform for IE10:
so pretend this is my checkbox (somewhat styled): [ A1 ]
Clicking somewhere inside the borders ( inside [ ] ) works. Checkbox is checked. But clicking directly on the Text (the Label, "A1") does not work, checkbox state does not change from unchecked to checked.
I added a console.log("..."); to fancyforms transformCheckbox-method right here:
check: function () {
console.log("setting check");
method.setProp(this, "checked", 1);
},
just showing me the same. "check" is not triggered, when I click at the label.
It would be great to get some hints here, for I am out of Ideas now.
Best Regards,
Dom
I had the same problem, in this case you need to bind the event because the IE version.
$(".select-row row-b label").bind('click',function(){
$('input',this).attr("checked",true);
})
Edit: Here's my working code, based on this answer. I edit this code inside here because there are several side effects you have to take care of:
this.$rowLbls = $(this.$el.find('.row-alter label')); //might be $('yourdomelement', 'yoursecond...'')
this.$rowLbls.click(function(event) {
var ele = $(this).find('input');
if( $(event.target).is("label") ) { //check exactly for label, because fired twice if not => would work just once
if(ele.is(':checked')){
ele.prop('checked', false); //prop instead of attr for true/false
} else{
ele.prop('checked', true);
}
}
});
I have a piece of jQuery code, which I use to check if a checkbox is not checked. If not, it throws an event. Here it is:
$('#Button').click(function() {
if(!$('input[#name=\"image_id\"]:checked').val()){
//Do Something
return false;
}
});
It works great, but i decided to style the default checkbox with jQuery Checkbox plugin.
Now heres the problem, This is what the output is after styling:
<input type="radio" name="answer_id" value="37" style="position: absolute; z-index: -1; visibility: hidden;">`
<span class="jquery-safari-checkbox jquery-safari-checkbox-checked"><span class="mark"><img src="empty.png"></span></span>
thus leaving me with no way to see if the input is checked. Any ideas on what I can do (if anything) or shall i just revert to the old checkboxes?
You don't have to do anything special. The original checkbox is still there and maintains its state. When you click the fancy checkbox, the plugin updates the hidden checkbox to match the current state.
You can update your code a little, too, if you use the latest jQuery. Your code is quite antiquated:
$('#Button').click(function () {
if (!$('input[name=image_id]').prop('checked')) {
//Do something
return false;
}
});
Demo: http://jsfiddle.net/k2d6E/
Kinda messy in my opinion to do this this way, but:
if($(".jquery-safari-checkbox").hasClass("jquery-safari-checkbox-checked")){
//Do something
return false;
}
i just met a strange behavior jQuery and can't figure out any more or less slight solution.
Say, i have textarea and button. I want to disable button if textarea is empty.
For this i have a handler which does this job.
Here is the code:
// textarea control
var $textarea = $('#myTextarea');
var $button = $('#myButton');
$textarea.on('input propertychange', function() {
if($textarea.val().length > 0) {
$button.removeClass('disabled').removeAttr('disabled');
} else {
$button.addClass('disabled').attr('disabled', 'disabled');
}
});
$button.on('click', function() {
if ($button.attr("disabled") != null) {
console.log('Disabled!');
return false;
} else {
// do some stuff and eventually erase textarea
$textarea.val('');
}
});
My trouble is when i erase textarea (the end of the code) it doesn't disable the button. Any ideas would be appreciated (actually it's slight adaptation of my code but the situation reflected pretty good, hope it would be clear for you, thanks!)
UPD
Nothing found on stackoverflow doesn't help.
UPD2
As i said in the begin, i was looking not for workaround like force trigger event, i thought it's possible to catch any event fired by $textarea.val(); Sure #Madbreaks and #epascarello 's solutions work pretty good, thanks guys.
Maybe just add this:
else {
// do some stuff and eventually erase textarea
$textarea.val('');
// notify
$textarea.trigger('propertychange');
}
problem is setting values with JavaScript does not normally trigger the events, but you can do it yourself.
$textarea.val('').trigger("input");
Make sure you trim the value of your textarea and you dont have an white spaces when you get the length of the .val(). Also in case you use a text editor like ckEditor make sure you read their documentation on how to retrieve the text being written.
Recommend using this jQueryTextChange lib. Its a cross browser consistent one. The usages are clearly elaborated on the home page. http://zurb.com/playground/jquery-text-change-custom-event
I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.