Radio button returning undefined value in javascript - javascript

http://jsfiddle.net/jngpjbjm/
Have a look at the fiddle link attached. Radio button value is returning a undefined value. I don't why. Please help with this.
<input type="radio" name="arv" value="1">1
<br>
<input type="radio" name="arv" value="2">2
var radio = document.getElementsByName('arv');
radio[0].addEventListener('click', check());
radio[1].addEventListener('click', check());
function check() {
for (var i = 0; i < radio.length; i++) {
var rcheck = radio[i].checked;
if (!rcheck) {
alert(rcheck.value);
}
}
}

Try this: http://jsfiddle.net/jngpjbjm/3/
It should be:
alert(radio[i].value);
Maybe you need something like this?
function check() {
alert( event.target.value );
}
http://jsfiddle.net/jngpjbjm/9/

I have tried to remove all excessive code from your original script as being unnecessary (kind of), whats left are the bare essentials. thanks #mplungjan
Try this:
var radio = document.getElementsByName('arv');
// here is how to add event listeners like the pros over at MDN
radio[0].addEventListener('click', check, false);
radio[1].addEventListener('click', check, false);
function check(e) {
//simply grab the event by passing it as "e" and capturing its target.value
var rcheck = e.target.value;
alert(rcheck);
}

Use this
var radio = document.getElementsByName('arv');
radio[0].addEventListener('click', check);
radio[1].addEventListener('click', check);
function check() {
for (var i = 0; i < radio.length; i++) {
var rcheck = radio[i].checked;
if (!rcheck) {
alert(radio[i].value);
}
}
}

This version will work in all browsers.
window.onload=function() {
var radios = document.getElementsByName('arv');
for (var i=0;i<radios.length;i++) {
radios[i].onclick=function() {
alert(this.value);
}
}
}
onclick
Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

Related

jQuery toggle not work when the argument are functions

I'm trying to use toggle() to complete my click events. In this case, I read the API, and use toggle(function1, function2, ...). But it was weird. The tag a just hide when I click it, rather than execute those functions inside.
Here is my javascript code.
function clickMe(){
$("#lime").toggle(
function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = true;
}
}
},function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = false;
}
}
}
) ;
}
And here is HTML code.
selectAll
<form>
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
</form>
I'm waiting for the comments. Thanks advance!
This functionality has been removed in jQuery 1.9.
Use this instead (works for older versions too):
$(function ($) {
var inputs = $('input[name=selectOne]');
$("#lime").click(function () {
inputs.prop( 'checked', ! inputs.prop('checked') );
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/
As pointed out by #Andre, if the first is checked by hand, it will then uncheck all. If that's not what you want, use this:
$(function ($) {
var inputs = $('input[name=selectOne]'),
flag = true;
$("#lime").click(function () {
inputs.prop( 'checked', flag );
flag = ! flag;
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/1/
$(function(){
var check = true;
$("#lime").click(function(){
$('input[name=selectOne]').prop('checked', check);
check = !check;
});
});
By doing this, you won't need the 'onclick' attribute in #lime element. Just remove it, and let jQuery bind the click handler for you. This is usually a good thing, as it separates structure and behaviour.
Edit:
If you need a function that reproduces old jQuery toggle behaviour, here's it:
(function($){
$.fn.toggleHandlers = function(eventType){
var i = 0;
var handlers = $.makeArray(arguments).slice(1);
return this.bind(eventType, function() {
handlers[i].apply(this, arguments);
if(i < handlers.length -1)
i++;
else
i = 0;
});
};
})(jQuery);
The difference from jQuery toggle is that it gets one extra parameter (the first one), that is the event type. So, it works with events other than click. Call it as:
$("#myElement").toggleHandlers('click', handler1, handler2[, handler3]);
See fiddle: http://jsfiddle.net/andreortigao/j9MH2/

javascript addEventListener firing on all elements

Im sure I have missed something obvious but any idea why the following addEventListener code is firing everywhere (on not just on the submit button)?
HTML:
<form action="#">
<input type="text"><br>
<input type="text"><br>
<button id="submit">submit</button><br>
</form>
JS:
function validate () {
var inputs = document.getElementsByTagName('input');
var inputs_length = inputs.length-1;
for (i=0; i<=inputs_length; i++) {
var inputs_value = document.getElementsByTagName('input')[i].value;
if (inputs_value == "") {
alert('there is a text box empty');
}
}
}
var el = document.getElementById('submit');
if (el.addEventListener) {
el = addEventListener('click', validate, false);
} else if (el.attachEvent) {
el.attachEvent('onclick', validate);
}
THE FIX IS CHANGE
el = addEventListener('click', validate, false);
TO
el.addEventListener('click', validate, false);
MY TYPO :(
Change this:
if (el.addEventListener) {
el = addEventListener('click', validate, false);
To this:
if (el.addEventListener) {
el.addEventListener('click', validate, false);
A lengthy comment.
In your code:
// inputs is an HTMLCollection of all the inputs
var inputs = document.getElementsByTagName('input');
// No need for the -1
var inputs_length = inputs.length;
// Don't forget to declare counters too, very important
// Just use < length
for (var i=0; i<inputs_length; i++) {
// Instead of this very inefficient method
var inputs_value = document.getElementsByTagName('input')[i].value;
// use the collection you already have
var inputs_value = inputs[i].value;
if (inputs_value == "") {
alert('there is a text box empty');
}
}
Also better to declare inputs_value at the beginning so all declarations are in one place, but as you have it is not harmful.
Oh, and don't give a form element a name or id of "submit" (or any other form method) as it will shadow the form method of the same name so it can't be called.

Javascript check/uncheck all function. IE doesn't update

function checkUncheckAll(theElement) {
var theForm = theElement.form, z = 0;
while (theForm[z].type == 'checkbox' && theForm[z].name != 'checkall') {
theForm[z].checked = theElement.checked;
z++;
}
}
theElement is the checkall checkbox at the bottom of a list of checkboxes. when clicked it calls this function to set all checkboxes in the same form to the value of checkall.
It works across all browsers aside from one glitch in IE. After clicking the checkall box it seems like the checkboxes are updated, but you don't see it. If you click anywhere on the page the checkboxes are then updated to their proper status. This happens for both checking and unchecking.
This is easy without jQuery, which is unnecessary here.
function checkUncheckAll(theElement) {
var formElements = theElement.form.elements;
for (var i = 0, len = formElements.length, el; i < len; ++i) {
el = formElements[i];
if (el.type == "checkbox" && el != theElement) {
el.checked = theElement.checked;
}
}
}
Update
It turned out the main problem was that the checkUncheckAll() function was being called from a change event handler on a checkbox, which doesn't fire in IE until the checkbox loses focus, so the fix was simply a matter of changing it to use a click event handler instead.
The best way to do this is to use jQuery. It does require including a library, but it's well worth it! jQuery handles cross-browser js/DOM issues, and provides an excellent selector syntax and modification methods.
Additional examples similar to yours are hilighted in this Blog Post:
http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery
function checkUncheckAll(theElement){
newvalue = $(theElement).is(':checked');
$("INPUT[type='checkbox']", theElement.form).attr('checked', newvalue);
}

IE7 issues with my jQuery [click and change functions]

I have the following snippets of code. Basically what I'm trying to do is in the 1st click function I loop through my cached JSON data and display any values that exist for that id. In the 2nd change function I capturing whenever one of the elements changes values (i.e. yes to no and vice versa).
These elements are all generated dynamically though the JSON data I'm receiving from a webservice. From my understanding that is why I have to use the .live functionality.
In Firefox everything works as expected (of course). However, in IE7 it does not. In IE7, if I select a radio button that displays an alert from the click function then it also adds to the array for the changed function. However, if the radio button does not do anything from the click function then the array is not added to for the change.
As I look at this code I'm thinking that I might be able to combine these 2 functions together however, right now I just want it to work in IE7.
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
});
});
$(document).ready(function () {
var blnCheck = false;
//Checks to see if values have changed.
//If a value has been changed then the isDirty array gets populated.
//This array is used when the questionSubmit button is clickeds
$('input').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
});
$('textarea').live('change', function () {
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("id")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("id");
arrayCount += 1;
//alert($(this).attr("name"));
}
});
});
UPDATE:
I had to move this chunk of code into the click function:
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
alert($(this).attr("name"));
}
Like this:
$(document).ready(function () {
//This function is run whenever a 'radio button' is selected.
//It then goes into the CPItemMetaInfoList in the cached JSON data
//($.myglobals) and checks to see if there are currently any
//scripts to display.
$("input:radio").live("click", function () {
var index = parseInt(this.name.split(':')[0]);
for (i = 0; i <= $.myglobals.result.length - 1; i++) {
if ($.myglobals.result[i].CPItemMetaInfoList.length > 0) {
for (j = 0; j <= $.myglobals.result[i].CPItemMetaInfoList.length - 1; j++) {
if (index == $.myglobals.result[i].QuestionId) {
alert($.myglobals.result[i].CPItemMetaInfoList[j].KeyStringValue);
return;
}
}
}
}
blnCheck = false;
for (i = 0; i <= isDirty.length - 1; i++) {
if (isDirty[i] == $(this).attr("name")) {
blnCheck = true;
break
}
}
if (blnCheck == false) {
isDirty[arrayCount] = $(this).attr("name");
arrayCount += 1;
}
});
});
But...
I had to leave the change function the same. From my testing I found that the .click function worked for IE7 for the radio buttons and checkbox elements, but the .change functionality worked for the textboxes and textareas in IE7 and FF as well as the original functionality of the radio buttons and checkbox elements.
This one got real messy. Thanks to #Patricia for looking at it. Here suggestions did lead me to this solution. I'm going to leave the question unanswered as I wonder if there isn't a cleaner solution to this.
Fact: change event on radio buttons and checkboxes only get fired when the focus is lost (i.e. when the blur event is about to occur). To achieve the "expected" behaviour, you really want to hook on the click event instead.
You basically want to change
$('input').live('change', function() {
// Code.
});
to
$('input:radio').live('click', functionName);
$('input:not(:radio)').live('change', functionName);
function functionName() {
// Code.
}
(I'd however also take checkboxes into account using :checkbox selector for the case that you have any in your form, you'd like to treat them equally as radiobuttons)
I think this is because IE fires the change when focus is lost on checks and radios. so if the alert is popping up, focus is being lost and therefor the change event is firing.
EDIT:
try changing the $('input') selector to $('input:not(:radio)')
so the click will fire for your radios and the change for all your others.
Edit #2:
How bout putting the stuff that happens on change into a separate function. with the index as a parameter. then you can call that function from the change() and the click(). put the call to that function after your done with the click stuff.
You're declaring your blnCheck variable inside one of your document.ready() functions. You don't need two of these either, it could all be in one.
This means that the variable that you're declaring there won't be the one used when your change function is actually called, instead you're going to get some kind of implicit global. Don't know if this is part of it, but might be worth looking at. You should declare this at the top of your JS file instead.

How can I check if a value is changed on blur event?

Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.
If it possible to check it the value is changed by user on the blur event of an input HTML element?
I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.
Within the onblur event, you can compare the value against the defaultValue to determine whether a change happened:
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
The defaultValue will contain the initial value of the object, whereas the value will contain the current value of the object after a change has been made.
References:
value vs defaultValue
You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.
I'd take an approach similar to this:
(function () {
var hasChanged;
var element = document.getElementById("myInputElement");
element.onchange = function () { hasChanged = true; }
element.onblur = function () {
if (hasChanged) {
alert("You need to change the value");
// blur event can't actually be cancelled so refocus using a timer
window.setTimeout(function () { element.focus(); }, 0);
}
hasChanged = false;
}
})();
Why not just maintaining a custom flag on the input element?
input.addEventListener('change', () => input.hasChanged = true);
input.addEventListener('blur', () => 
{
if (!input.hasChanged) { return; }
input.hasChanged = false;
// Do your stuff
});
https://jsfiddle.net/d7yx63aj
Using Jquery events we can do this logic
Step1 : Declare a variable to compare the value
var lastVal ="";
Step 2: On focus get the last value from form input
$("#validation-form :input").focus(function () {
lastVal = $(this).val();
});
Step3:On blur compare it
$("#validation-form :input").blur(function () {
if (lastVal != $(this).val())
alert("changed");
});
You can use this code:
var Old_Val;
var Input_Field = $('#input');
Input_Field.focus(function(){
Old_Val = Input_Field.val();
});
Input_Field.blur(function(){
var new_input_val = Input_Field.val();
if (new_input_val != Old_Val){
// execute you code here
}
});
I know this is old, but I figured I'd put this in case anyone wants an alternative. This seems ugly (at least to me) but having to deal with the way the browser handles the -1 index is what was the challenge. Yes, I know it can be done better with the jquery.data, but I'm not that familiar with that just yet.
Here is the HTML code:
<select id="selected">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
Here is the javascript code:
var currentIndex; // set up a global variable for current value
$('#selected').on(
{ "focus": function() { // when the select is clicked on
currentIndex = $('#selected').val(); // grab the current selected option and store it
$('#selected').val(-1); // set the select to nothing
}
, "change": function() { // when the select is changed
choice = $('#selected').val(); // grab what (if anything) was selected
this.blur(); // take focus away from the select
//alert(currentIndex);
//setTimeout(function() { alert(choice); }, 0);
}
, "blur": function() { // when the focus is taken from the select (handles when something is changed or not)
//alert(currentIndex);
//alert($('#selected').val());
if ($('#selected').val() == null) { // if nothing has changed (because it is still set to the -1 value, or null)
$('#selected').val(currentIndex); // set the value back to what it originally was (otherwise it will stay at what was newly selected)
} else { // if anything has changed, even if it's the same one as before
if ($('#selected').val() == 2) { // in case you want to do something when a certain option is selected (in my case, option B, or value 2)
alert('I would do something');
}
}
}
});
Something like this. Using Kevin Nadsady's above suggestion of
this.value!=this.defaultValue
I use a shared CSS class on a bunch of inputs then do:
for (var i = 0; i < myInputs.length; i++) {
myInputs[i].addEventListener('blur', function (evt) {
if(this.value!=this.defaultValue){
//value was changed now do your thing
}
});
myInputs[i].addEventListener('focus', function (evt) {
evt.target.setAttribute("value",evt.target.value);
});
}
Even if this is an old post, I thought i'd share a way to do this with simple javascript.
The javascript portion:
<script type="text/javascript">
function HideLabel(txtField){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value=='YOURBOXNAME')
txtField.value = '';
else
txtField.select();
}
}
function ShowLabel(YOURBOXNAME){
if(txtField.name=='YOURBOXNAME'){
if(txtField.value.trim()=='')
txtField.value = 'YOURDEFAULTVALUE';
}
}
</script>
Now the text field in your form:
<input type="text" id="input" name="YOURBOXNAME" value="1" onfocus="HideLabel(this)"
onblur="ShowLabel(this)">
And bewn! No Jquery needed. just simple javascript. cut and paste those bad boys. (remember to put your javascript above the body in your html)
Similar to #Kevin Nadsady's post, the following will work in native JS functions and JQuery listener events. Within the onblur event, you can compare the value against the defaultValue:
$(".saveOnChange").on("blur", function () {
if (this.value != this.defaultValue) {
//Set the default value to the new value
this.defaultValue = this.value;
//todo: save changes
alert("changed");
}
});
The idea is to have a hidden field to keep the old value and whenever the onblur event happens, check the change and update the hidden value with the current text value
string html = "<input type=text id=it" + row["cod"] + "inputDesc value='"
+ row["desc"] + "' onblur =\"if (this.value != document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value){ alert('value change'); document.getElementById('hd" + row["cod"].ToString() +
"inputHiddenDesc').value = this.value; }\"> " +
"<input type=hidden id=hd" + row["cod"].ToString() + "inputHiddenDesc value='" + row["desc"] + "'>";

Categories

Resources